窗体定义热键,用一个文本框做定义,保存在文本文件中:文本框name:txt_hotkey
文本框属性更改:ReadOnly=true;
以下是文本框的需要的事件:
private void txt_hotkey_KeyDown(object sender, KeyEventArgs e)
{
string control = "";
string key = "";
if (e.Modifiers.ToString() != "None")
{
control = e.Modifiers.ToString().Replace(",", " +");
string keydata = e.KeyData.ToString().Substring(0, e.KeyData.ToString().IndexOf(","));
if (keydata == "Menu" || keydata == "ControlKey" || keydata == "ShiftKey")
{
key = "";
//key = e.Modifiers.ToString() + "|" + e.KeyData.ToString().Substring(0, e.KeyData.ToString().IndexOf(","));
}
else
{
key = e.KeyData.ToString().Substring(0, e.KeyData.ToString().IndexOf(","));
//key = e.Modifiers.ToString() + "|" + e.KeyData.ToString().Substring(0, e.KeyData.ToString().IndexOf(","));
}
}
else
{
key = e.KeyData.ToString();
}
if (e.Modifiers.ToString() != "None")
{
if (txt_hotkey.Text.Substring(txt_hotkey.Text.Length) == " ")
{
txt_hotkey.Text = "";
}
else
{
txt_hotkey.Text = control + " + " + key + "";
}
}
else
{
if (txt_hotkey.Text.Substring(txt_hotkey.Text.Length) == " ")
{
txt_hotkey.Text = txt_hotkey.Text + "+" + key;
}
else
{
txt_hotkey.Text = key;
}
}
//txt_hotkey.Text= Func.Win32.KeyModifiers.Ctrl.ToString();
}
private void txt_hotkey_KeyUp(object sender, KeyEventArgs e)
{
if (txt_hotkey.Text.Length >= 1)
{
if (txt_hotkey.Text.Substring(txt_hotkey.Text.Length - 1) == " ")
{
txt_hotkey.Text = "";
}
}
}
定义完毕后保存事件:
FileData file = new FileData(); //此类后面会介绍
try
{
file.WriteCom(txt_hotkey.Text);
Win32 win = new Win32();//定义注册热键的函数,后面会列出
win.regkey(Handle, 100, txt_hotkey.Text.Trim().Replace(" ", ""));//handle为要注册的窗体的Handle
win.regkey(Handle, 101, txt_Show.Text.Trim().Replace(" ", ""));
}
catch (Exception ee)
{
file.WriteError("保存错误:" + ee.Message);
}
finally
{
file = null;
}
以下为win32类定义:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Drawing;
public class Win32
{
#region windows函数引用 定义热键
//定义了辅助键的名称(将数字转变为字符以便于记忆,也可去除此枚举而直接使用数值)
[Flags()]
public enum KeyModifiers
{
None = 0,
Alt = 1,
Ctrl = 2,
Shift = 4,
WindowsKey = 8,
CtrlAndShift = 6
}
[DllImport("user32.dll",SetLastError=true)]
public static extern bool RegisterHotKey( IntPtr hWnd, //要定义热键的窗口的句柄
int id, //定义热键ID(不能与其它ID重复) //标识热键是否在按Alt、Ctrl、Shift、Windows等键时才会生效
int fsModifiers,
Keys vk //定义热键的内容
);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool UnregisterHotKey( IntPtr hWnd, //要取消热键的窗口的句柄
int id //要取消热键的ID
);
#endregion
/// <summary>
/// 注册热键
/// </summary>
/// <param name="Handle">要注册热键的窗体句柄</param>
/// <param name="id">注册的热键ID</param>
/// <param name="hotkey">热键</param>
public void regkey(IntPtr Handle,int id,string hotkey)
{
//FileData fd = new FileData();
////获取热键
//string hotkey = fd.ReadHotKey();
string[] keystr = hotkey.Split('+');
if (keystr.Length > 0)
{
Keys key = Keys.None;
int Modifiers = 0;
//注册热键Ctrl+Alt+0,Id号为100。KeyModifiers.CtrlAndAlt也可以直接使用数字3来表示。
KeysConverter kc = new KeysConverter();
if (keystr.Length == 2)
{
Modifiers = getkeycode(keystr[0]);
key = (Keys)kc.ConvertFromString(keystr[1]);
}
else if (keystr.Length == 3)
{
int Modifiers1 = getkeycode(keystr[0]);
int Modifiers2 = getkeycode(keystr[1]);
Modifiers = Modifiers1 + Modifiers2;
key = (Keys)kc.ConvertFromString(keystr[2]);
}
else
{
key = (Keys)kc.ConvertFromString(keystr[0]);
}
removekey(Handle, id);
if (!Func.Win32.RegisterHotKey(Handle, id, Modifiers, key))
{
MessageBox.Show("[" + hotkey + "]快捷键注册失败,可能已被其他程序占用,请更换或重试!");
}
}
else
{
MessageBox.Show("没有设定快捷键或快捷键设定不正确!");
}
}
public bool removekey(IntPtr Handle, int id)
{
return Func.Win32.UnregisterHotKey(Handle, id);
}
public int getkeycode(string key)
{
//None = 0,
//Alt = 1,
//Ctrl = 2,
//Shift = 4,
//WindowsKey = 8,
int keycode = 0;
switch (key)
{
case "Alt": keycode = 1; break;
case "Menu": keycode = 1; break;
case "Ctrl": keycode = 2; break;
case "Control": keycode = 2; break;
case "ControlKey": keycode = 2; break;
case "Shift": keycode = 4; break;
case "ShiftKey": keycode = 4; break;
case "WindowsKey": keycode = 8; break;
case "Windows": keycode = 8; break;
default: keycode = 0; break;
}
return keycode;
}
}
FileData类,存储热键
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.IO;
namespace Func
{
public class FileData
{
public FileData()
{ }
public static string GetDirectory()
{
return System.AppDomain.CurrentDomain.BaseDirectory;
}
const string SPLIT = ",";
const string FILENAME = "config.txt";
//保存热键在配置文件中
public bool WriteCom(string hotkey)
{
string path = GetDirectory() + FILENAMECOM;
try
{
FileStream stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter write = new StreamWriter(stream, Encoding.UTF8);
write.WriteLine( key1.Trim().Replace(" ", "") );
write.Close();
stream.Close();
return true;
}
catch (Exception ee)
{
throw ee;
}
}
//读取热键字符串
public string ReadHotKey()
{
string path = GetDirectory() + FILENAMECOM;
string HotKey = "";
if (!File.Exists(path))
return HotKey;
else
{
FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
//Model.Member m = null;
if (reader.Peek() > -1)
{
HotKey = reader.ReadLine();
}
reader.Close();
stream.Close();
return HotKey;
}
}
以下为使用窗体代码:
在窗体的构造函数中写入以下代码:
Win32 win = new Win32();
FileData file = new FileData();
string key1 = file.ReadHotKey();
if (key1!="")
win.regkey(Handle, (int)HotKeyID.read, key1);//HotKeyID为本人写的枚举
重写使用窗体的以下事件:
protected override void WndProc(ref Message m)
{
const int WM_HOTKEY = 0x0312;
switch (m.Msg)
{
case WM_HOTKEY:
switch (m.WParam.ToInt32())
{
case (int)HotKeyID.read:
// 这里写热键要执行的动作
break;
}
break;
}
base.WndProc(ref m);
}
以下补充为上述本人使用的枚举:
public enum HotKeyID : int
{
read = 100
}