Mouse cursor outside of form

2019-07-26 17:48发布

问题:

I have an old color picker utility written c++ that I coded years back and want to rewrite using c#.

I implemented the global hook to pick pixels off the screen and so on. Everything is ok but...

The cross cursor reverts to the pointer once the mouse moves outside the form and onto the desktop. This does not happen with my c++ code (MFC actually).

How is this accomplished in c#?

Thank you all.

(I'm using this http://www.codeproject.com/Articles/7294/Processing-Global-Mouse-and-Keyboard-Hooks-in-C for the hook)

回答1:

The solution (or a workaround) is to simulate the first part of a mouse click event. This will lock the mouse on the calling window, thus preserving the chosen cursor.

[DllImport( "user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall )]
public static extern void mouse_event( uint dwFlags, uint dx, uint dy, uint cButtons, uint dwExtraInfo );

private const int   MOUSEEVENTF_LEFTDOWN    = 0x02;
private const int   MOUSEEVENTF_LEFTUP      = 0x04;
private const int   MOUSEEVENTF_RIGHTDOWN   = 0x08;
private const int   MOUSEEVENTF_RIGHTUP     = 0x10;

And then after enabling the mouse capture in the code:

mouse_event(
    MOUSEEVENTF_LEFTDOWN,
    (uint)Cursor.Position.X,
    (uint)Cursor.Position.Y,
    0,
    0 );

this.Cursor = Cursors.Cross;

Hope it helps.