Getting Position of mouse cursor when clicked out side the form's boundary

前端 未结 5 1236
轻奢々
轻奢々 2020-12-06 08:00

It is very easy to get the position of cursor out side the form\'s boundary by just dragaging the mouse it sends many values to the form when ever the position changes, form

5条回答
  •  自闭症患者
    2020-12-06 08:36

    The solution to this problem is simple. All what you need is a System.Windows.Forms.Timer, and use System.Runtime.InteropService.DllImport to extern the method GetKeyState from user32.dll.

    This function has one parameter of any type of integer, and it returns short (Int16). This function can tell you if some keys were pressed or not at every moment and everywhere, not depending on the form. While the Timer is Enabled, you can check if the mouse position is out of the form bounds. There are many ways to get the mouse position.

    One way is Cursor.Position, or Control.MousePosition, or you can use the bool GetCursorPos(ref Point lpPoint), an extern method, that you can DllImport it from "user32.dll". form.Bounds or form.ClientRectangle, or form.Location and form.Size or form.Left and form.Top and form.Width and form.Height, all these bring you the form bounds. In the timer_Tick function event, you write the following code for example:

    var mp = Cursor.Position;
    var fb = form.ClientRectangle; // Or form.Bounds
    
    if (mp.X < fb.X || mp.Y < fb.Y || mp.X > fb.X + fb.Width || mp.Y > fb.Y + fb.Height)
    {
        // Use GetKeyState from user32.dll to detect if at least 1 key is pressed
        // (look at internet how to do it exactly)
        // If yes MessageBox.Show("Clicked outside");
    }
    

    If at least 1 key was pressed, and then Show your message with the MessageBox. You can read on the Internet how to do all these stuff I was talking about before, and if you succeed, it will work!

提交回复
热议问题