如何创建SendMessage WM_KEYDOWN的lParam

时间:2012-04-23 11:51:56

标签: c# interop pinvoke

我正在尝试使用SendMessage发送击键,并且不太了解lParam。据我所知,不同的位代表每个参数,需要按顺序排列。

我看过this question& this,所以我知道这些位需要的顺序,我只是不知道该怎么做......

如何创建以下lParam?

repeat cound = 0,
scan code = {Don't know what this is?},
extended key = 1,
reserved = 0,
context code = 0,
previous key state = 1,
transition state = 0

2 个答案:

答案 0 :(得分:9)

我意识到AutoIT具有我需要的功能,所以看了source文件sendKeys.cpp并找到了这个函数的以下C ++代码片段,它很容易翻译进入C#:

scan = MapVirtualKey(vk, 0);

// Build the generic lparam to be used for WM_KEYDOWN/WM_KEYUP/WM_CHAR
lparam = 0x00000001 | (LPARAM)(scan << 16);         // Scan code, repeat=1
if (bForceExtended == true || IsVKExtended(vk) == true)
    lparam = lparam | 0x01000000;       // Extended code if required

if ( (m_nKeyMod & ALTMOD) && !(m_nKeyMod & CTRLMOD) )   // Alt without Ctrl
    PostMessage(m_hWnd, WM_SYSKEYDOWN, vk, lparam | 0x20000000);    // Key down, AltDown=1
else
    PostMessage(m_hWnd, WM_KEYDOWN, vk, lparam);    // Key down

可以使用MapVirtualKey

生成扫描代码

C#翻译:

public static void sendKey(IntPtr hwnd, VKeys keyCode, bool extended)
{
    uint scanCode = MapVirtualKey((uint)keyCode, 0);
    uint lParam;

    //KEY DOWN
    lParam = (0x00000001 | (scanCode << 16));
    if (extended)
    {
        lParam |= 0x01000000;
    }
    PostMessage(hwnd, (UInt32)WMessages.WM_KEYDOWN, (IntPtr)keyCode, (IntPtr)lParam);

    //KEY UP
    lParam |= 0xC0000000;  // set previous key and transition states (bits 30 and 31)
    PostMessage(hwnd, WMessages.WM_KEYUP, (uint)keyCode, lParam);
}

[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern uint MapVirtualKey(uint uCode, uint uMapType);

答案 1 :(得分:1)

如果你必须使用SendMessage,那么你需要在正确的位置切换int的位。

本网站介绍了如何在C#中执行此操作:

http://codeidol.com/csharp/csharpckbk2/Classes-and-Structures/Turning-Bits-On-or-Off/

参考您的问题,ScanCode是您尝试发送的密钥的值,也代表某些状态。例如,按A的扫描码与释放A的码不同。

维基百科有一篇关于它们的文章:

http://en.wikipedia.org/wiki/Scancode