简体   繁体   中英

How to detect mouse clicks?

how can i detect mouse clicks on Windows ? (XP/Vista/7). for example when my application is running , it will detect if user click on something (not on that application UI but on Windows UI). if yes , execute another process.

I don't know if this is possible , i am hoping someone can give me some guidance.

Thanks!

You need to write a mouse hook if you want to intercept any mouse clicks, movement, mouse wheel clicks...etc.

This is the only way AFAIK if you want to track mouse activity outside of your own application. You need to import the SetWindowsHookEx(...) function from the User32.dll file if you want to install a hook. It involves interop (PInvoke) and you'll have to import (DllImport) some functions.

Here's an official document by Microsoft on how to achieve this in C#:

How to set a Windows hook in Visual C# .NET

I'll summarize it here, just to be complete the answer should the link die one day.

Starting with the SetWindowsHookEx function:

[DllImport("user32.dll",CharSet=CharSet.Auto,
 CallingConvention=CallingConvention.StdCall)]
public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, 
IntPtr hInstance, int threadId);

Now you can setup your hook. For example:

public class Form1
{
    static int hHook = 0;
    public delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);
    HookProc MouseHookProcedure;

    private void ActivateMouseHook_Click(object sender, System.EventArgs e)
    {
        if(hHook == 0)
        {
            MouseHookProcedure = new HookProc(Form1.MouseHookProc);
            hHook = SetWindowsHookEx(WH_MOUSE, 
                             MouseHookProcedure,
                             (IntPtr) 0,
                             AppDomain.GetCurrentThreadId());
        }
    }
}

Don't forget to unhook it afterwards. You'll need another DllImport for this:

[DllImport("user32.dll",CharSet=CharSet.Auto,
CallingConvention=CallingConvention.StdCall)]
public static extern bool UnhookWindowsHookEx(int idHook);

private void DeactivateMouseHook_Click(object sender, System.EventArgs e)
{
    bool ret = UnhookWindowsHookEx(hHook);
}    

You can use the HookProc delegate (MouseHookProcedure) to capture the mouse activity. This involves some marshalling in order to capture the data.

[StructLayout(LayoutKind.Sequential)]
public class POINT 
{
    public int x;
    public int y;
}

[StructLayout(LayoutKind.Sequential)]
public class MouseHookStruct 
{
    public POINT pt;
    public int hwnd;
    public int wHitTestCode;
    public int dwExtraInfo;
}

public static int MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{          
    MouseHookStruct MyMouseHookStruct = (MouseHookStruct)
        Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));

    // You can get the coördinates using the MyMouseHookStruct.
    // ...       
    return CallNextHookEx(hHook, nCode, wParam, lParam); 
}

Don't forget to call the next item in the hook chain afterwards (CallNextHookEx)!

[DllImport("user32.dll",CharSet=CharSet.Auto,      
 CallingConvention=CallingConvention.StdCall)]
public static extern int CallNextHookEx(int idHook, int nCode, 
IntPtr wParam, IntPtr lParam);

PS: You can do the same for the keyboard.

Windows hooking mechanism is what you need to work with. Take a look at this article: Processing Global Mouse and Keyboard Hooks in C#

While Christophe Geers solution helps you to capture the mouse event, it does not provide a complete solution to the issue. Edward wanted to know how to get the click event.

To get the click event, use the solution provided by Christophe Geers. And add/edit the following:

enum MouseMessages
{
    WM_LBUTTONDOWN = 0x0201,
    WM_LBUTTONUP = 0x0202,
    WM_MOUSEMOVE = 0x0200,
    WM_MOUSEWHEEL = 0x020A,
    WM_RBUTTONDOWN = 0x0204,
    WM_RBUTTONUP = 0x0205
}

public static int MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{
    //Marshall the data from the callback.
    MouseHookStruct MyMouseHookStruct = (MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));

    if (nCode >= 0 &&
        MouseMessages.WM_LBUTTONDOWN == (MouseMessages)wParam)
    {
        // Do something here
    }
    return CallNextHookEx(hookHandle, nCode, wParam, lParam);
}

All you need is a mouse hook. It can detect your mouse movement or clicks. You can download the demo here: C# mouse_hook_Demo
When you press your mouse and release it, you will see the event on the richtextbox.

private void mh_MouseDownEvent(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                richTextBox1.AppendText("Left Button Press\n");
            }
            if (e.Button == MouseButtons.Right)
            {
                richTextBox1.AppendText("Right Button Press\n");
            }
        }

        private void mh_MouseUpEvent(object sender, MouseEventArgs e)
        {

            if (e.Button == MouseButtons.Left)
            {
                richTextBox1.AppendText("Left Button Release\n");
            }
            if (e.Button == MouseButtons.Right)
            {
                richTextBox1.AppendText("Right Button Release\n");
            }

        }
        private void mh_MouseClickEvent(object sender, MouseEventArgs e)
        {
            //MessageBox.Show(e.X + "-" + e.Y);
            if (e.Button == MouseButtons.Left)
            {
                string sText = "(" + e.X.ToString() + "," + e.Y.ToString() + ")";
                label1.Text = sText;
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM