如何在C#中实现全局热键? [英] How to implement Global Hotkeys in C#?

查看:190
本文介绍了如何在C#中实现全局热键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个全局拦截Alt + Shift + S的应用程序.

I need to write an application which globally intercepts Alt+Shift+S.

我所做的是创建了一个设置全局挂钩的DLL:

What I did is I created a DLL which sets global hooks:

namespace Hotkeydll
{
    public class MyHotKey
    {
        public static void setHooks()
        {
            KeyboardHookProcedure = new HookProc(KeyboardHookProc);
            hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardHookProcedure, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);
        }

        private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
        {
            //write something into file
        }


   }
}

然后,我创建了一个程序,该程序加载了该DLL并设置了钩子:

Then I created a program which loads this DLL and set the hook:

using Hotkeydll;
namespace IWFHotkeyStarter
{
    class Program
    {
        static void Main(string[] args)
        {
            MyHotKey.setHooks();
        }
    }
}

现在的问题是热键不起作用.

Now the problem is that the hotkey doesn't work.

似乎DLL没有永久加载到内存中.我看到我可以从文件系统中删除dll文件.

It looks like the DLL is not loaded permanently into memory. I see that I can delete the dll file from file system.

所以请告知我我做错了什么?

So please advise what I am doing wrong?

我应该使用其他方法吗?

Should I use a different approach?

谢谢.

推荐答案

您的Main()方法设置挂钩,然后立即退出并终止程序.此外,您需要一个消息循环来使钩子回调工作.这需要Windows Forms或WPF应用程序.现在,使用真实的热键代替挂钩也成为一种选择.检查此线程例如,C#在页面的下方.

Your Main() method sets the hooks, then immediately exits and terminates the program. Furthermore, you need a message loop to make the hook callback work. That requires a Windows Forms or WPF app. Using a real hot key instead of a hook now also becomes an option. Check this thread for an example, C# is further down the page.

这篇关于如何在C#中实现全局热键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆