Search code examples
c#console-applicationmouseevent

How to simulate mouse button 4 and mouse button 5 click in C#?


I am trying to create a tool to manipulate user32.dll. I want to add a function that you can simulate a mouse click, but i want to add all the available mouse buttons, like M4 (mouse button 4) and M5 (mouse button 5). I didn't find any documentation showing how to simulate these buttons. So, i decided to ask here in Stack Overflow to see if someone knows how to do this.

I tried looking for documentation, but i didn't find anything that answered my question.


Solution

  • Using the cursor position, you can send a message to a window that the extra mouse buttons are clicked. You most likely want WM_XBUTTONDOWN and WM_XBUTTONUP.

    WM_XBUTTONDOWN: https://learn.microsoft.com/en-us/windows/win32/inputdev/wm-xbuttondown

    WM_XBUTTONUP: https://learn.microsoft.com/en-us/windows/win32/inputdev/wm-xbuttonup

     [DllImport("User32.dll", EntryPoint = "SendMessage")]
        private static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
    
     [DllImport("user32.dll")]
        static extern IntPtr WindowFromPoint(System.Drawing.Point p);
    
    
    IntPtr windowHandel = WindowFromPoint(new System.Drawing.Point(500, 500));
    
    //Extra mouse button one
    SendMessage(windowHandel, 0x020B, (IntPtr)0x00010000, new IntPtr());//Click
    SendMessage(windowHandel, 0x020C, (IntPtr)0x00010000, new IntPtr());//Release
    
    //Extra mouse button two click
    SendMessage(windowHandel, 0x020B, (IntPtr)0x00020000, new IntPtr());//Click
    SendMessage(windowHandel, 0x020C, (IntPtr)0x00020000, new IntPtr());//Release