powershell 注册全局热键
01 前言
在处理一些重复工作问题的时候,想搞一个小工具,配合全局快捷键来提高效率。因为是Windows系统,想到C#,但是又不想用VS开发,因为那样不够灵活,没办法随时修改随时用,所以只能另寻他法。那么,不如用powershell来搞搞。
02 正文
因为涉及到全局热键,所以还是需要写一点C#,引入一些API,同时加了一个简单的窗体。
环境:Windows 11
代码如下:
<#
注册全局热键
by hokis
2024-04-30 21:35
#>
$code = @'
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class GlobalHotkey
{
public const int MOD_ALT = 0x0001; // Alt键
public const int MOD_CTRL = 0x0002; // Ctrl键
public const int MOD_SHIFT = 0x0004; // Shift键
public const int MOD_WIN = 0x0008; // Windows键
private const int WM_HOTKEY = 0x0312;
private Action<object, EventArgs> hotkeyAction;
private int id;
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, Keys vk);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
public GlobalHotkey(IntPtr hWnd, Keys key, int modifier, Action<object, EventArgs> action)
{
hotkeyAction = action;
id = this.GetHashCode();
RegisterHotKey(hWnd, id, modifier, key);
Application.AddMessageFilter(new MessageFilter(this));
}
public void Unregister(IntPtr hWnd)
{
UnregisterHotKey(hWnd, id);
}
private class MessageFilter : IMessageFilter
{
private GlobalHotkey hotkey;
public MessageFilter(GlobalHotkey hotkey)
{
this.hotkey = hotkey;
}
public bool PreFilterMessage(ref Message m)
{
if (m.Msg == WM_HOTKEY && (int)m.WParam == hotkey.id)
{
hotkey.hotkeyAction(null, EventArgs.Empty);
return true;
}
return false;
}
}
}
'@
Add-Type -TypeDefinition $code -ReferencedAssemblies 'System.Windows.Forms'
Add-Type -AssemblyName 'System.Windows.Forms'
#全局对象
[GlobalHotkey]$Global:hotkey = $null
<#
热键被按下,事件处理
#>
$action = [System.Action[System.Object,System.EventArgs]]{
param(
$obj,
$er
)
Write-Host '热键被按下了...'
#提醒
[System.Media.SystemSounds]::Beep.Play()
}
<#
.Synopsis
窗体结构