问题:
我有一个活动的 WPF 窗口。在创建时,进程被设置为窗口的所有者。现在,当在 WPF 窗口上触发 Key-Down 事件时,应将 Key 传递给主进程。
首先,我使用 SetForegroundWindow() 将焦点设置为主进程。密钥是使用 InputSimulator 发送的。
到目前为止,这按预期工作。但是,在发送 Key 之后,Wpf 窗口应该重新获得焦点,以便它可以捕获下一次按键。
我正在尝试在 WPF 窗口上调用 Activate()。现在出现的问题是 InputSimulator 发送的 Key 不再传递给主进程,而是被 WPF Window 捕获。
代码
继承人的代码:
这是Window的创建
public void createWindow()
{
CommandLineWindow win = new CommandLineWindow();
helper = new WindowInteropHelper(win);
Process oCurrent = Process.GetCurrentProcess();
var ww = new WindowWrapper(oCurrent.MainWindowHandle);
helper.Owner = oCurrent.MainWindowHandle;
win.ShowDialog();
}
WindowWrapper 的实现:
public class WindowWrapper : System.Windows.Forms.IWin32Window
{
public WindowWrapper(IntPtr handle)
{
_hwnd = handle;
}
public IntPtr Handle
{
get { return _hwnd; }
}
private IntPtr _hwnd;
}
还有我的 Window.KeyDown 处理程序:
private void Window_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.X)
{
//Do something
SetForegroundWindow(helper.Owner);
new InputSimulator().Keyboard.KeyDown(WindowsInput.Native.VirtualKeyCode.VK_Y);
this.Activate();
}
}