开发者

Implement mouse over and mouse click event for specified screen region

开发者_JAVA技巧

I have some specified region on the screen (not on the form, but on the screen), for example, it's region in the upper-right corner of the screen.

Rectangle specifiedRegion = new Rectangle(*,*,*,*);

I want to implement mouse over and mouse click event for that region. When mouse was over that region, some button or picture appeared in that region. If user clicked that region, mouse click event executed.

How can I do it ? Please, provide some code or good links.

C#, VS 2008, .net 2.0, 3.5


Just a warning before we get started that the solution isn't going to be pretty, AFAIK you cannot do this completely within managed code.

Now then:

In order to intercept messages to other application you are going to need to make some native calls using User32.dll. If you want to figure all this out the hard way you want to start with SetWindowsHookEx.

Assuming you aren't a masochist there is a nice C# library I found on CodeProject that will make life much easier than manually trying to intercept those messages yourself. Setup a callback for the mouse messages with the X and Y coordinates for the mouse position you can determine if it is within the bounds of your Rectangle using its Contains method.

specifiedRegion.Contains(mouseLocation); //where mouseLocation is a Point

User32 also has the functions you will need to get a Device Context for the screen:

[DllImport("User32.dll")]
public static extern IntPtr GetDC(IntPtr hwnd);

[DllImport("User32.dll")]
public static extern void ReleaseDC(IntPtr dc);

To get the DC for the screen use the following call to GetDC:

IntPtr screenDC = GetDC(IntPtr.Zero);

With this DC we can get our C# Graphics object and start drawing.

Graphics g = Graphics.FromHdc(screenDC);

Remember to dispose the Graphics object and release the DC after you finish with it or you will have a memory leak.

g.Dispose();
ReleaseDC(screenDC);


There is a very simple way to do this. Just make a panel control in the region you want this to happen. Use the mousemove and mouseclick events of the panel control to capture your inputs, and you can even copy whatever image you want directly to the panel. This encapsulates the entire operation within the panel, avoiding the need for handling outside the panel class.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜