2014-05-01 40 views
0

我試圖通過使用WinAPI來模擬一些關鍵事件。我想按WIN鍵,但我的代碼不工作。在例子中,我爲每個proc使用VK_F1。模擬鍵盤事件不起作用C#

using System; 
using System.Diagnostics; 
using System.Runtime.InteropServices; 

namespace ConsoleApplication69 
{ 
    class Program 
    { 
     const UInt32 WM_KEYDOWN = 0x0100; 
     const UInt32 WM_KEYUP = 0x0101; 
     const int VK_F1 = 112; 

     [DllImport("user32.dll", CharSet = CharSet.Auto)] 
     static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam); 

     static void Main(string[] args) 
     { 
      Process[] processes = Process.GetProcesses(); 

      foreach (Process proc in processes) 
      { 
       SendMessage(proc.MainWindowHandle, WM_KEYDOWN, new IntPtr(VK_F1), IntPtr.Zero); 
       SendMessage(proc.MainWindowHandle, WM_KEYUP, new IntPtr(VK_F1), IntPtr.Zero); 
      } 
     } 
    } 
} 
+0

我一直使用'PostMessage'而不是'SendMessage',也許它也適用於你。 – aevitas

回答

1

要模擬鍵盤輸入,請使用SendInput。這正是這個API所做的。 「將F1發送到每個窗口」並不是一個好主意,因爲您會將鍵擊發送到沒有鍵盤焦點的窗口。誰知道他們會如何迴應。

鍵盤輸入的細微差別遠遠超出您的估計; See this question for considerations about emulating keyboard input

+0

我還沒有hwnd :) –

0

所以我用代碼從這個網址:SendKeys.Send and Windows Key

,它工作正常!

using System.Runtime.InteropServices; 
using System.Windows.Forms; 

namespace ConsoleApplication69 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      KeyboardSend.KeyDown(Keys.LWin); 
      KeyboardSend.KeyUp(Keys.LWin); 
     } 
    } 

    static class KeyboardSend 
    { 
     [DllImport("user32.dll")] 
     private static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo); 

     private const int KEYEVENTF_EXTENDEDKEY = 1; 
     private const int KEYEVENTF_KEYUP = 2; 

     public static void KeyDown(Keys vKey) 
     { 
      keybd_event((byte)vKey, 0, KEYEVENTF_EXTENDEDKEY, 0); 
     } 

     public static void KeyUp(Keys vKey) 
     { 
      keybd_event((byte)vKey, 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0); 


} 


} 

}

TNX的幫助大家!