Search code examples
c#.netcontextmenusendkeys

Right click with SendKeys in .NET


I am using sendkeys in C# .NET. I have letters, arrow keys and enter working. I cant figure out how to send a right click for the context menu. I know i can press a key on my keyboard to do it but i have no idea how to send the msg. How do i? i googled and saw

new MenuItem().PerformClick();

as a solution however i didnt see any affect. The keys are being sent to another application.


Solution

  • You can wrap the user32.dll, I got the general idea from here

    EDIT: I added in posX and posY, which would be the mouse coordinates.

    using System;
    using System.Runtime.InteropServices;
    
    namespace WinApi
    {  
        public class Mouse
        { 
                [DllImport("user32.dll")]
                private static extern void mouse_event(UInt32 dwFlags,UInt32 dx,UInt32 dy,UInt32 dwData,IntPtr dwExtraInfo);
    
                private const UInt32 MouseEventRightDown = 0x0008;
                private const UInt32 MouseEventRightUp = 0x0010;
    
                public static void SendRightClick(UInt32 posX, UInt32 posY)
                {
                    mouse_event(MouseEventRightDown, posX, posY, 0, new System.IntPtr());
                    mouse_event(MouseEventRightUp, posX, posY, 0, new System.IntPtr());
                }    
        }
    }