C# winform 定义软件的热键或快捷键

发布时间:2009年07月29日      浏览次数:1341 次
将下面的代码保存为hotkey.cs类文件
================================
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace MySoft.Inc
{
class hotkey
{
[DllImport("user32.dll", SetLastError = true)]
public static extern bool RegisterHotKey(
IntPtr hWnd,
int id,
KeyModifiers fsModifiers,
Keys vk
);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool UnregisterHotKey(
IntPtr hWnd,
int id
);
[Flags()]
public enum KeyModifiers
{
None = 0,
Alt = 1,
Ctrl = 2,
Shift = 4,
WindowsKey = 8
}
}
}
================================
将以下代码放到你的主要窗体中
================================
#region 系统热键的定义
private void Frame_main_Activated(object sender, EventArgs e)
{
//注册热键Alt+`,Id号为100。
hotkey.RegisterHotKey(Handle, 100, hotkey.KeyModifiers.Alt, Keys.Oemtilde);
}
private void Frame_main_Leave(object sender, EventArgs e)
{
//注销Id号为100的热键设定
hotkey.UnregisterHotKey(Handle, 100);
}
/// 监视Windows消息
/// 重载WndProc方法,用于实现热键响应
protected override void WndProc(ref Message m)
{
const int WM_HOTKEY = 0x0312;
//按快捷键
switch (m.Msg)
{
case WM_HOTKEY:
switch (m.WParam.ToInt32())
{
case 100:
/////////////////////////////////////////////
// 在此写当按你定义的热键时的动作
// 我在此的代码是将系统最小化到托盘,或从托盘恢复主要窗体的原大小
/////////////////////////////////////////////
if (this.Visible == true)
{
this.Visible = false;
this.Frame_main_min.Visible = true;
}
else
{
this.Visible = true;
this.Activate();
this.Frame_main_min.Visible = false;
}
/////////////////////////////////////////////
break;
}
break;
}
base.WndProc(ref m);
}
#endregion
需要在你的主要窗体中的Activated事件中加上Frame_main_Activated,在Leave事件中加上Frame_main_Leave即可。
文章来源:桂林唯创网络
免责声明:本站相关技术文章信息部分来自网络,目的主要是传播更多信息,如果您认为本站的某些信息侵犯了您的版权,请与我们联系,我们会即时妥善的处理,谢谢合作!