我在C ++中使用此代码将密钥事件发送到不同的应用程序。
struct extraKeyInfo
{
unsigned short repeatCount;
unsigned char scanCode;
bool extendedKey, prevKeyState, transitionState;
operator unsigned int()
{
return repeatCount | (scanCode << 16) | (extendedKey << 24) |
(prevKeyState << 30) | (transitionState << 31);
}
};
void SendK(HWND wnd, Char ch, DWORD del)
{
short vkCode = LOBYTE(VkKeyScan(ch));
extraKeyInfo lParam = {};
lParam.scanCode = MapVirtualKey(vkCode, MAPVK_VK_TO_VSC);
PostMessage(wnd, WM_KEYDOWN, vkCode, lParam);
lParam.repeatCount = 1;
lParam.prevKeyState = true;
lParam.transitionState = true;
Sleep(del);
PostMessage(wnd, WM_KEYUP, vkCode, lParam);
}
我真的需要在C#中使用THIS方法。我知道我可以从user32.dll导入PostMessage和MapVirtualKey函数,如下所示
[DllImport("user32.dll")]
public static extern bool PostMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
[DllImport("user32.dll")]
public static extern uint MapVirtualKey(uint uCode, uint uMapType);
但是我坚持使用lParam变量。我不知道如何在C#中转换那些标志位。必须有办法。
修改。完成并完成 在Jashaszun的小建议之后。
[DllImport("user32.dll")]
public static extern bool PostMessage(IntPtr hWnd, uint Msg, uint wParam, int lParam);
[DllImport("user32.dll")]
public static extern uint MapVirtualKey(uint uCode, uint uMapType);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern short VkKeyScan(char ch);
const uint WM_KEYDOWN = 0x0100;
const uint WM_KEYUP = 0x0101;
const uint MAPVK_VK_TO_VSC = 0x00;
const uint MAPVK_VSC_TO_VK = 0x01;
const uint MAPVK_VK_TO_CHAR = 0x02;
const uint MAPVK_VSC_TO_VK_EX = 0x03;
const uint MAPVK_VK_TO_VSC_EX = 0x04;
class extraKeyInfo
{
public ushort repeatCount;
public char scanCode;
public ushort extendedKey, prevKeyState, transitionState;
public int getint()
{
return repeatCount | (scanCode << 16) | (extendedKey << 24) |
(prevKeyState << 30) | (transitionState << 31);
}
};
public static void SendK(IntPtr wnd, Char ch, Int32 del)
{
uint vkCode = (byte)(VkKeyScan(ch));
extraKeyInfo lParam = new extraKeyInfo();
lParam.scanCode = (char)MapVirtualKey(vkCode, MAPVK_VK_TO_VSC);
PostMessage(wnd, WM_KEYDOWN, vkCode, lParam.getint());
lParam.repeatCount = 1;
lParam.prevKeyState = 1;
lParam.transitionState = 1;
System.Threading.Thread.Sleep(del);
PostMessage(wnd, WM_KEYUP, vkCode, lParam.getint());
}
SendK函数将指定的char发送到具有指定保持延迟的指定窗口。