2011-10-11 91 views
0

我有这样的代码:PostMessage到当前活动进程不适用于所有进程?

const UInt32 WM_KEYDOWN = 0x0100; 

    const int VK_DOWN = 0x28; 
    const int VK_UP = 0x26; 

    [DllImport("user32.dll")] 
    static extern bool PostMessage(IntPtr hWnd, UInt32 Msg, int wParam, int lParam); 

    [DllImport("user32.dll")] 
    private static extern IntPtr GetForegroundWindow(); 

    [DllImport("user32.dll")] 
    private static extern Int32 GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId); 

    private static Process GetProcessByHandle(IntPtr hwnd) 
    { 
     try 
     { 
      uint processID; 
      GetWindowThreadProcessId(hwnd, out processID); 
      return Process.GetProcessById((int)processID); 
     } 
     catch { return null; } 
    } 

    public static Process GetActiveProcess() 
    { 
     IntPtr hwnd = GetForegroundWindow(); 
     return hwnd != null ? GetProcessByHandle(hwnd) : null; 
    } 

    public static void KeyUp() 
    { 
     PostMessage(GetActiveProcess().MainWindowHandle, WM_KEYDOWN, VK_UP, 0); 
    } 

    public static void KeyDown() 
    { 
     PostMessage(GetActiveProcess().MainWindowHandle, WM_KEYDOWN, VK_DOWN, 0); 
    } 

当我打电话的KEYUP /的KeyDown它仅适用于某些过程,proccess如文本editos,视觉工作室。

但在Explorer.exe中,iTunes.exe,的chrome.exe,的Outlook.exe,FileZilla.exe多不工作..

我跑控制台调试:

while (true) 
    { 
     Process currentProcess = GetActiveProcess(); 
     if (currentProcess != null) 
      Console.WriteLine(currentProcess.MainWindowTitle); 
     Thread.Sleep(1000); 
    } 

在这里我从一些应用程序得到:

ProjName - Microsoft Visual Studio (Administrator) 
?PostMessage to Current Active Proccess doesn't work for all proccess ? - StackOverFlow - Google Chrome? 
FileZilla 
Inbox - Outlook Data File - Microsoft Outlook 

而且在Explorer.exe中,我得到空行..

+0

的可能重复的[PostMessage的WM_KEYDOWN发送乘法键?](http://stackoverflow.com/questions/7732633/postmessage-wm-keydown-send-multiply-keys) –

回答

1

有在Windows应用程序中读取键盘状态的多种方式,并且响应WM_KEYDOWNWM_KEYUP只是其中之一。应用程序也可以使用GetKeyStateGetAsyncKeyState。应用程序也可以响应WM_CHARWM_SYSKEYDOWNWM_SYSKEYUP消息。不同的应用程序将使用不同的方法,如果您没有模拟应用程序正在寻找的应用程序,它将不会响应。

您遇到的问题与Raymond链接到的问题稍有不同,但解决方案可能相同。即使用SendInput代替PostMessage的

+0

我不能使用SendInput因为我的进程没有集中.. – Danpe

+0

@Danpe尝试发送'WM_SYSKEYDOWN'除'WM_KEYDOWN'。这可能适用于大多数应用程序。 – IronMensan

相关问题