Skip to main content
 首页 » 编程设计

c#之PostMessage 在 Windows 7 x64 中不起作用

2024年02月23日15webabcd

我需要在游戏窗口中模拟按键。我尝试发送 key “A”,但它不起作用:

[DllImport("user32.dll", SetLastError = true)] 
static extern IntPtr FindWindow(string lpClassName, string lpWindowName); 
 
[DllImport("USER32.DLL")] 
public static extern bool SetForegroundWindow(IntPtr hWnd); 
 
[DllImport("user32.dll")] 
public static extern IntPtr PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam); 
 
private void button1_Click(object sender, EventArgs e) 
{ 
    IntPtr hWnd = FindWindow(null, "Game Name");  // it's work! 
 
    if (hWnd == IntPtr.Zero) 
    { 
        MessageBox.Show("Game is not running"); 
        return; 
    } 
 
    SetForegroundWindow(hWnd);  // it's work too and now I have active window of game 
    System.Threading.Thread.Sleep(3000); 
 
    const int WM_KEYDOWN = 0x0100; 
    PostMessage(hWnd, WM_KEYDOWN, (IntPtr)Keys.A, IntPtr.Zero);     // don't work ;-( 
} 

请您参考如下方法:

你得到了什么错误?游戏是否以管理员身份运行?您可能会被 UIPI 屏蔽.