C#基础(DllImport)

发布于:2025-07-02 ⋅ 阅读:(24) ⋅ 点赞:(0)

🧙‍♂️ ​​1. 什么是 DllImport?​

  • ​一句话解释​​:DllImport 是 C# 的“借书证”,用来借 Windows 系统自带的“魔法工具”(比如弹出消息框、播放声音)。

📝 ​​2. 超简单三步魔法!​

✅ ​​第一步:告诉电脑你要借谁的魔法​
using System.Runtime.InteropServices; // 先拿好“借书证”
✅ ​​第二步:写下魔法咒语(DllImport)​
[DllImport("kernel32.dll")]          // 借的是 Windows 的“魔法书”(kernel32.dll)
public static extern bool Beep(      // 咒语名字叫 Beep(叮咚声)
    int frequency,                   // 音调(数字越大越尖)
    int duration                     // 持续时间(数字越大越长)
);
✅ ​​第三步:念咒语!​
Beep(500, 1000); // 叮咚!500Hz 音调,持续1秒

🌟 ​​实际例子:点按钮就弹出消息框​

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

public class MagicClass
{
    // 1️⃣ 借一个“弹出消息框”的魔法(来自 user32.dll)
    [DllImport("user32.dll")]
    public static extern int MessageBox(
        IntPtr hWnd,         // 不用管,写 IntPtr.Zero 就行
        string text,          // 消息内容(比如“你好呀!”)
        string caption,      // 标题(比如“小学生的魔法”)
        int buttons          // 按钮样式(0=只有确定按钮)
    );

    // 2️⃣ 做个按钮触发魔法
    public static void Main()
    {
        // 点按钮就弹窗!
        MessageBox(IntPtr.Zero, "我会用 DllImport 啦!", "🎉 魔法成功", 0);
    }
}

进阶代码

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

public class MainForm : Form
{
    // 1. 声明Windows API函数 - 注册/注销热键 [1,4](@ref)
    [DllImport("user32.dll")]
    private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);

    [DllImport("user32.dll")]
    private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

    // 2. 定义组合键枚举(Alt/Ctrl/Shift等)[1](@ref)
    [Flags]
    private enum KeyModifiers
    {
        None = 0,
        Alt = 1,    // Alt键
        Ctrl = 2,   // Ctrl键
        Shift = 4   // Shift键
    }

    // 3. 热键常量
    private const int WM_HOTKEY = 0x0312;    // 系统热键消息标识
    private const int HOTKEY_ID = 100;        // 自定义热键ID(任意唯一数字)

    // 4. 窗体构造函数
    public MainForm()
    {
        // 窗体初始化代码
        this.Text = "快捷键示例";
        this.Load += MainForm_Load;          // 窗体加载时注册热键
        this.FormClosing += MainForm_Closing; // 关闭时注销热键
    }

    // 5. 窗体加载时注册热键
    private void MainForm_Load(object sender, EventArgs e)
    {
        // 注册 Ctrl+Alt+R 组合键:
        // this.Handle -> 当前窗体句柄
        // HOTKEY_ID -> 热键唯一标识
        // (uint)(KeyModifiers.Ctrl | KeyModifiers.Alt) -> 组合键Ctrl+Alt
        // (uint)Keys.R -> 字母R键
        bool success = RegisterHotKey(this.Handle, HOTKEY_ID, 
            (uint)(KeyModifiers.Ctrl | KeyModifiers.Alt), 
            (uint)Keys.R);

        if (!success)
        {
            MessageBox.Show("热键注册失败!可能已被其他程序占用");
        }
    }

    // 6. 重写消息处理函数 - 监听热键消息
    protected override void WndProc(ref Message m)
    {
        if (m.Msg == WM_HOTKEY && m.WParam.ToInt32() == HOTKEY_ID)
        {
            ShowInputDialog(); // 触发显示输入框
        }
        base.WndProc(ref m); // 继续传递其他消息
    }

    // 7. 显示输入框的方法
    private void ShowInputDialog()
    {
        using (var inputForm = new Form())
        {
            inputForm.Text = "快捷键触发";
            var textBox = new TextBox { Width = 200, Top = 20, Left = 20 };
            var btnOk = new Button { Text = "确定", Top = 50, Left = 20 };

            btnOk.Click += (s, e) => inputForm.Close();

            inputForm.Controls.Add(textBox);
            inputForm.Controls.Add(btnOk);
            inputForm.ShowDialog(); // 模态显示输入框
        }
    }

    // 8. 窗体关闭时注销热键
    private void MainForm_Closing(object sender, FormClosingEventArgs e)
    {
        UnregisterHotKey(this.Handle, HOTKEY_ID); // 清理系统热键资源
    }

    // 9. 程序入口
    [STAThread]
    static void Main()
    {
        Application.Run(new MainForm()); // 启动窗体
    }
}


网站公告

今日签到

点亮在社区的每一天
去签到