如何在C#中使用全局热键来回更改应用程序焦点



我正在创建我自己的C#剪贴板管理器,我有一个全局热键ALT+H,它将触发从剪贴板中删除文本格式。我的应用程序在后台运行,只有托盘图标。因此,这很好,但我的问题是,当我在一个应用程序中时,例如Word,我按下热键,它会显示这些应用程序中的所有菜单,我不希望这样。

仅供参考,这与我目前在SO上的另一个问题非常相关,如何停止在C#中进一步处理全局热键。在另一个问题中,这是基于找到热键的解决方案,但另一种方法,我认为可能更好,可以是将焦点临时切换到我的应用程序,一旦我的热键不再适用,则可以将焦点切换回原始应用程序。

然而,我不知道如何再次切换回原始应用程序!?

到目前为止,我的代码只关注应用程序更改机制hmn:

程序:

// Import the required "SetForegroundWindow" method
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);

Form1.cs:

// Change focus to my application (when hotkey is active)
Program.SetForegroundWindow(this.Handle);

我不完全确定这是否真的有效,但我可以看到原始应用程序(例如Word(失去了焦点,我的应用程序仍然可以正常工作,所以我希望它可以正常工作。

我的问题是——如何从原始应用程序获得hWnd(?(句柄,以便在完成后切换回它?如果我在任何应用程序中都而不是,而只是在WIndows桌面上呢?然后会发生什么?它能变回那样吗?

我很感激任何可以帮助我的提示,因为我还不是真正的C#开发人员;-(

我自己找到了解决方案,并将解释我的解决方案

using System.Runtime.InteropServices;
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
// I get in to here when the clipboard has changed and I need to find the application that has changed the clipboard
// Get the active/originating application handle
IntPtr originatingHandle = GetForegroundWindow();
// ------------------
// Do "some stuff" - this is not required for the application switching but it will get the application process name for the active/originating application
// Get the process ID from the active application
uint processId = 0;
GetWindowThreadProcessId(originatingHandle, out processId);
// Get the process name from the process ID
string appProcessName = Process.GetProcessById((int)processId).ProcessName;
// End "some stuff"
// ------------------
// Change focus to my application - this code is inside my main form (Form1)
SetForegroundWindow(this.Handle);
// Do some more stuff - whatever is required for my application to do
// ...
// Change focus back to the originating application again
SetForegroundWindow(originatingHandle);

至少上面的代码对我有效。

相关内容

最新更新