Right click with SendKeys in .NET

若如初见. 提交于 2019-12-07 02:35:28

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());
            }    
    }
}

Assuming you are referring to the key positioned a few places right of the spacebar, which performs the same operation as the right mouse button in some situations, {MENU} may be the special key you want to send. It is not implemented in some SendKeys variations, and I am unsure of the latest version of C#.NET.

You cannot send mouse input using the .NET SendKeys class. At least, not that I know of nor that's documented. The best way to do this is to switch to the WinAPI and use the SendInput method. You can use this in .NET using DllImport for the function (in "user32.dll") and StructLayout for the structures.

Then you will want to call it like this:

INPUT pressRight;
pressRight.type = MOUSE; // = 0
pressRight.mi.dx = 0;
pressRight.mi.dy = 0;
pressRight.mi.mouseData = 0;
pressRight.mi.dwFlags = MOUSEEVENTF_RIGHTDOWN; // = 8
pressRight.mi.time = 0;
pressRight.mi.dwExtraInfo = IntPtr.Zero;

INPUT releaseRight = pressRight;
releaseRight.mi.dwFlags = MOUSEEVENTF_RIGHTUP; // = 10

INPUT[] inputs = new INPUT[2];
inputs[0] = pressRight;
inputs[1] = releaseRight;

SendInput(2, inputs, Marshal.SizeOf(typeof(INPUT)));

The {MENU} key is not always avialable, as noted by @Sparr. However, shift-F10 brings up the context menu in most Windows applications. So SendKeys.SendWait("+{F10}"); should work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!