2014-09-23 75 views
0

如何將外部窗口模擬爲聚焦窗口? 我需要這個,因爲我想把鑰匙發送到記事本窗口,它只有在記事本窗口有焦點時才起作用。但我不想把焦點放在我自己的窗口上。模擬要聚焦的窗口

public IntPtr Find(string taskName, string windowName) 
{ 
    return Fenster.FindWindow(taskName, windowName); 
} 
public void Send(IntPtr hwnd, string text) 
{ 
    if (!hwnd.Equals(IntPtr.Zero)) 
    { 
     SendKeys.Send(text); 
    } 
} 
public bool SetForeground(IntPtr hwnd) 
{ 
    return SetForegroundWindow(hwnd); 
} 

[DllImport("user32.dll", EntryPoint = "FindWindow")] 
private static extern IntPtr FindWindow(string lp1, string lp2); 

[DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)] 
[return: MarshalAs(UnmanagedType.Bool)] 
private static extern bool SetForegroundWindow(IntPtr hWnd); 

非常感謝!

+0

你不能,或者至少你不想。將正確的消息發送到記事本,不要使用SendKeys。 – CodeCaster 2014-09-23 11:25:22

+0

有沒有另一種方法發送不使用Sendkeys的密鑰? – Thomas 2014-09-23 11:27:27

+0

現在你問的是正確的問題。看到重複。 :)使用'SendMessage()'你可以[發送'WM_CHAR'消息到窗口的消息隊列](http://stackoverflow.com/questions/13514820/sendmessage-when-to-use-keydown-syskeydown-etc) ,模擬按鍵到一個沒有焦點的窗口。 – CodeCaster 2014-09-23 11:30:43

回答

1

最好的解決辦法是讓你想控制和發送鍵消息窗口HWND - 直接通過SendMessagePostMessage(無論是WM_KEY_DOWNWM_KEY_UPWM_CHAR可能取決於應用和目的)。