问题
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.
回答1:
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());
}
}
}
回答2:
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.
回答3:
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)));
回答4:
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.
来源:https://stackoverflow.com/questions/2024088/right-click-with-sendkeys-in-net