+
95
-

回答

在C#中,你可以使用RegisterHotKey函数来注册全局快捷键,并在相应的处理函数中隐藏和显示主窗体。以下是一个示例代码,展示了如何实现这一功能:

首先,确保你已经添加了对System.Runtime.InteropServices命名空间的引用。

然后,使用以下代码来注册快捷键并处理相应的操作:

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

public class MainForm : Form
{
    private const int HOTKEY_ID = 9000;

    // Import the RegisterHotKey function from user32.dll
    [DllImport("user32.dll", SetLastError = true)]
    private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);

    // Import the UnregisterHotKey function from user32.dll
    [DllImport("user32.dll", SetLastError = true)]
    private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

    public MainForm()
    {
        InitializeComponent();
        RegisterHotKey();
    }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        Application.ApplicationExit += OnApplicationExit;
    }

    private void OnApplicationExit(object sender, EventArgs e)
    {
        UnregisterHotKey();
    }

    protected override void WndProc(ref Message m)
    {
        if (m.Msg == 0x0312 && m.WParam.ToInt32() == HOTKEY_ID)
        {
            ToggleVisibility();
        }

        base.WndProc(ref m);
    }

    private void RegisterHotKey()
    {
        // Register the hotkey (Ctrl + Shift + H)
        if (!RegisterHotKey(this.Handle, HOTKEY_ID, (uint)(ModifierKeys.Control | ModifierKeys.Shift), (uint)Keys.H))
        {
            MessageBox.Show("Hotkey registration failed!");
        }
    }

    private void UnregisterHotKey()
    {
        UnregisterHotKey(this.Handle, HOTKEY_ID);
    }

    private void ToggleVisibility()
    {
        if (this.Visible)
        {
            this.Hide();
        }
        else
        {
            this.Show();
        }
    }

    private void InitializeComponent()
    {
        this.SuspendLayout();
        // 
        // MainForm
        // 
        this.ClientSize = new System.Drawing.Size(284, 261);
        this.Name = "MainForm";
        this.Load += new System.EventHandler(this.MainForm_Load);
        this.ResumeLayout(false);
    }

    private void MainForm_Load(object sender, EventArgs e)
    {
    }
}

在这个示例中:

RegisterHotKey 和 UnregisterHotKey 函数用于注册和注销全局快捷键。WndProc 方法用于处理Windows消息,当接收到注册的快捷键消息时,调用 ToggleVisibility 方法来隐藏或显示主窗体。ToggleVisibility 方法根据当前窗体的可见性来决定是隐藏还是显示窗体。

请注意,全局快捷键需要在窗体加载时注册,并在应用程序退出时注销。这样可以确保快捷键在应用程序运行期间有效,并在应用程序关闭时释放资源。

网友回复

我知道答案,我要回答