应用事件解决方案
private IKeyboardMouseEvents m_ApplHook;
private void FormName_Activated(object sender, EventArgs e) {
m_ApplHook = Hook.AppEvents(); // Subscribe
Action d = () => { Dop.ChangeBackColor(this, Color.Black); };
Action s = () => { Dop.ChangeBackColor(this, Color.Red); };
// Install listener App [Combinations]
m_ApplHook.OnCombination(new Dictionary<Combination, Action> {
{ Combination.FromString("Control + S"), d },
{ Combination.FromString("Control + D"), s }
});
}
private void FormName_Deactivate(object sender, EventArgs e) {
m_ApplHook.Dispose(); // UnSubscribe
}
GlobalEvents 的解决方案(如果您的应用程序中只有 1 个表单)
在 FormName_Load 中激活 GlobalEvents
private IKeyboardMouseEvents m_GlobalHook;
private void FormName_Load(object sender, EventArgs e) {
m_GlobalHook = Hook.GlobalEvents();
// Install Global listener [Sequences]
Sequence OpenApps = Sequence.FromString("Control + C, Control + C");
Dictionary<Sequence, Action> assignments = new Dictionary<Sequence, Action> {
{ OpenApps, () => {
this.Text = Clipboard.GetText();
}},
};
// Replace Hook.GlobalEvents() on m_GlobalHook
m_GlobalHook.OnSequence(assignments);
}
停用 FormName_Closed 中的 GlobalEvents(非强制性:关闭主窗体将关闭整个应用程序
private void FormName_FormClosed(object sender, FormClosedEventArgs e) {
m_GlobalHook.Dispose();
}
GlobalEvents 的解决方案(如果您的应用程序中有超过 1 个表单)
使用 Hide() 隐藏所需的表单,打开另一个表单。根据这本书(http://it-kniga.narod.ru/5-7502-0222-4/02020903.html),方法 Hide() 类似于 Visible = false;
创建 FormName_VisibleChanged 事件。以所有必要的形式编写代码(例如:FormMain、Form1、FormName...)。此方法允许您为每个单独的表单而不是所有正在运行(隐藏)的表单激活 GlobalEvents。
private IKeyboardMouseEvents m_GlobalHook;
// Documentation: https://github.com/gmamaladze/globalmousekeyhook/blob/vNext/keycomb.md
private void FormName_VisibleChanged(object sender, EventArgs e) {
if (this.Visible) {
m_GlobalHook = Hook.GlobalEvents(); // Subscribe
Action ex = () => { this.Text += "Ctrl + C x2"; };
Action ext = () => { this.Text += "Shift + C"; };
// Install Global listener [Sequences]
m_GlobalHook.OnSequence(new Dictionary<Sequence, Action> {
{ Sequence.FromString("Control + C, Control + C"), ex },
{ Sequence.FromString("Shift + C"), ext },
});
} else m_GlobalHook.Dispose(); // UnSubscribe
}