powershell 注册全局热键——提升效率小工具

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
       窗体结构
  
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值