`

使用C#注册全局快捷键

阅读更多

天试了一下这个, 记录下来, 以后我给自己做小工具时, 肯定用的到.

 

注册/注销全局快捷键需要用user32.dll中的这两个api:

RegisterHotKey

UnregisterHotKey

所以使用C#注册全局快捷键就是要用C#调用user32.dll中的这两个函数,

 

问题1 C#调用dll

这其中涉及的问题有:

1.为了使用[DllImport("user32.dll")], 要先using System.Runtime.InteropServices;

2.import的函数要用static extern来修饰.

 

关于C#调用dll的介绍可以参考下面这几个链接:

 

在 C# 中通过 P/Invoke 调用Win32 DLL

Calling Win32 DLLs in C# with P/Invoke

这两个link一个是中文版, 一个是英文版, 还有代码示例可以下载. 其中还有个类型映射表, 比较有帮助.

这些都是基本类型, 指针的后面有说明.


Win32 Types Specification CLR Type
char, INT8, SBYTE, CHAR† 8-bit signed integer System.SByte
short, short int, INT16, SHORT 16-bit signed integer System.Int16
int, long, long int, INT32, LONG32, BOOL†, INT 32-bit signed integer System.Int32
__int64, INT64, LONGLONG 64-bit signed integer System.Int64
unsigned char, UINT8, UCHAR†, BYTE 8-bit unsigned integer System.Byte
unsigned short, UINT16, USHORT, WORD, ATOM, WCHAR†, __wchar_t 16-bit unsigned integer System.UInt16
unsigned, unsigned int, UINT32, ULONG32, DWORD32, ULONG, DWORD, UINT 32-bit unsigned integer System.UInt32
unsigned __int64, UINT64, DWORDLONG, ULONGLONG 64-bit unsigned integer System.UInt64
float, FLOAT Single-precision floating point System.Single
double, long double, DOUBLE Double-precision floating point System.Double
†In Win32 this type is an integer with a specially assigned meaning; in contrast, the CLR provides a specific type devoted to this meaning.

 

还有这几篇也不错

暴强贴:从.NET平台调用Win32 API

Platform Invoke Tutorial

 

 

问题2:  注册/注销全局快捷键

C#封装得真是很简单, 得到一个窗口的句柄只需要对Form调用this.Handle即可.

 

具体实现可以参考下面这两篇帖子:

C#注册全局热键

在c#中使用全局快捷键

 

附件是在第二个帖子基础上写的代码,他对dll中导入的api又做了一次封装, vs2008的工程.

分享到:
评论
2 楼 wjason 2009-10-15  
工具(Tray Friend):将任何程序,最小化到系统托盘

在我这篇blog中也有对一工具的使用。
1 楼 wjason 2009-05-08  
一定要覆写WndProc这个方法, 这次写的时候犯了这个错误....
        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            Hotkey.ProcessHotKey(m);
        }

相关推荐

Global site tag (gtag.js) - Google Analytics