欢迎光临

木子屋

标题: C#设置全局热键

作者: dnawo

日期: 2009-08-28 06:03 PM

分类: Win编程

内容: Hotkey.cs：
复制内容到剪贴板 程序代码using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public delegate void HotkeyEventHandler(int hotkeyid);
public class Hotkey : IMessageFilter
{
Hashtable keyIDs = new Hashtable();
IntPtr hWnd;
public event HotkeyEventHandler OnHotkey;
public enum KeyFlags
{
MOD_ALT = 0x1,
MOD_CONTROL = 0x2,
MOD_SHIFT = 0x4,
MOD_WIN = 0x8
}
[DllImport("user32.dll")]
public static extern UInt32 RegisterHotKey(IntPtr hWnd, UInt32 id, UInt32 fsModifiers, UInt32 vk);
[DllImport("user32.dll")]
public static extern UInt32 UnregisterHotKey(IntPtr hWnd, UInt32 id);
[DllImport("kernel32.dll")]
public static extern UInt32 GlobalAddAtom(String lpString);
[DllImport("kernel32.dll")]
public static extern UInt32 GlobalDeleteAtom(UInt32 nAtom);
public Hotkey(IntPtr hWnd)
{
this.hWnd = hWnd;
Application.AddMessageFilter(this);
}
public int RegisterHotkey(Keys key, KeyFlags keyflags)
{
UInt32 hotkeyid = GlobalAddAtom(Guid.NewGuid().ToString());
RegisterHotKey((IntPtr)hWnd, hotkeyid, (UInt32)keyflags, (UInt32)key);
keyIDs.Add(hotkeyid, hotkeyid);
return (int)hotkeyid;
}
public void UnregisterHotkeys()
{
Application.RemoveMessageFilter(this);
foreach (UInt32 key in keyIDs.Values)
{
UnregisterHotKey(hWnd, key);
GlobalDeleteAtom(key);
}
}
public bool PreFilterMessage(ref Message m)
{
if (m.Msg == 0x312)
{
if (OnHotkey != null)
{
foreach (UInt32 key in keyIDs.Values)
{
if ((UInt32)m.WParam == key)
{
OnHotkey((int)m.WParam);
return true;
}
}
}
}
return false;
}
}
}
Form1.cs：
复制内容到剪贴板 程序代码using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private Hotkey _hotkey;
private int _hotkeyid;
public Form1()
{
InitializeComponent();
}
public void OnHotkey(int hotkeyid)
{
if (hotkeyid == _hotkeyid)
{
if (this.Visible == true)
this.Visible = false;
else
this.Visible = true;
}
else
{
this.Visible = false;
}
}
private void Form1_Load(object sender, EventArgs e)
{
_hotkey = new Hotkey(this.Handle);
_hotkeyid = _hotkey.RegisterHotkey(Keys.F2, Hotkey.KeyFlags.MOD_CONTROL); //定义快键(Ctrl + F2)
_hotkey.OnHotkey += new HotkeyEventHandler(OnHotkey);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
_hotkey.UnregisterHotkeys();
}
}
}

+ 查看当前日志评论 (2)

登录

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 1.812 ms

返回

标题: C#设置全局热键

你没有权限发表评论

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 1.812 ms

返回

标题: C#设置全局热键

评论内容:

== dnawo 2009-09-07 06:16 PM ----

代码都在上边了，测试过的，Copy就能用。

== ztitan 2009-09-06 12:34 AM ----

你好，请问你能发这个程序的源文件给我吗？我邮箱是199989277@qq.com，打扰你拉~~

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 5.109 ms

返回