开发者

Cursor over WinForm control (c#, WinForm 4.0)

开发者 https://www.devze.com 2023-02-23 22:49 出处:网络
What is the easiest way to determine if my current cursor position is over a particular (WinForm) control?

What is the easiest way to determine if my current cursor position is over a particular (WinForm) control?

I can - of course - calculate the control's position and then check whether the cursor position is within this rectangel. But maybe there is something already existing for this....

I cannot use OnMouseOver event for this, because the decisions must take place within (another) event. In order to further explain here is what I do (in pseudo code). The problem is, when I start the drag event, then move to another control (outside this), release the mouse to finish the drop, the context menu is displayed on the "wrong" control (the drop target). This is what I want to avoid....

 private void TableControlMouseDown(object sender, MouseEventArgs e)
    {
        ...
        // this开发者_JAVA技巧 is a User control with some sub controls 

        // when selected start drag and drop
        if (SOMEConditions)
        {
            // start drag and drop operation
            DragAndDropWrapper dragAndDropWrapper = new DragAndDropWrapper(this.ObjectsToDrag, this);
            this._subControl.DoDragDrop(dragAndDropWrapper, DragDropEffects.Copy);
        }

        // context menu

        // check should go here
        // something like "is pt still over "this" or over the drag target ...
        Point pt = this._subControl.PointToClient(Control.MousePosition);
        this._myContextMenu.Show(this._subControl, pt);
    }

-- as of today -- See below for the extension method I am using at the moment ...


You can declare:

bool insideMyControl = false;

Then trap MouseEnter (and set insideMyControl = true) and MouseLeave events (and set insideMyControl = false) on the particular control.
Then in your event look insideMyControl value.


This is the best solution I have found so far. Actually it is pretty easy (as always once you know how to do it ;-) since PointToClient gives me relative coordinates which drastically reduces the effort .... As an extension method it also is easy to use with all controls.

    /// <summary>
    ///   Is the mouse pointer over the control?
    /// </summary>
    /// <param name = "control"></param>
    /// <returns></returns>
    public static bool IsMouseOverControl(this Control control)
    {
        if (control == null) throw new ArgumentNullException("control");
        Contract.EndContractBlock();

        Point pt = control.PointToClient(Control.MousePosition);
        return (pt.X >= 0 && pt.Y >= 0 && pt.X <= control.Width && pt.Y <= control.Height);
    }


Did you tried GetCursorPos WIN32 API function

Try this.

Point p = new Point();
GetCursorPos(ref p);
0

精彩评论

暂无评论...
验证码 换一张
取 消