当前位置: 首页 > news >正文

C#基础(DllImport)

🧙‍♂️ ​​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()); // 启动窗体}
}

http://www.lqws.cn/news/594091.html

相关文章:

  • CppCon 2018 学习:Better C++ using Machine Learning on Large Projects
  • [Python 基础课程]字符串
  • Tomcat9部署jsp产生错误FileCountLimitExceededException
  • 网络安全监测探针功能
  • Python 数据分析:DataFrame,生成,用字典创建 DataFrame ,键值对数量不一样怎么办?
  • python+uniapp基于微信小程序的PS社区系统
  • 基于3D卷积神经网络与多模态信息融合的医学影像肿瘤分类与可视化分析
  • JVM调优实战 Day 15:云原生环境下的JVM配置
  • Go 服务如何“主动”通知用户?SSE广播与断线重连实战
  • 【算法】动态规划:python实现 1
  • 前端开发git的使用(常用命令和规范)
  • Python ORM 完全指南:从基础到高级实践
  • UI前端大数据可视化实战技巧分享:如何选择合适的颜色与图表类型?
  • MATLAB构建capm和三因子模型
  • t检验​、​z检验、χ²检验中的P值
  • rabbitmq动态创建交换机、队列、动态绑定,销毁
  • 企业上网行为管理:零信任安全产品的对比分析
  • go语言安装达梦数据完整教程
  • 大数据在UI前端的应用创新研究:基于自然语言处理的用户意图识别
  • Spring生态的核心组件演进
  • 21、鸿蒙学习——使用App Linking实现应用间跳转
  • 推客系统小程序终极指南:从0到1构建自动裂变增长引擎,实现业绩10倍增长!
  • 使用tensorflow的线性回归的例子(二)
  • 【第二章:机器学习与神经网络概述】04.回归算法理论与实践 -(2)支持向量回归(SVR)
  • linux魔术字定位踩内存总结
  • GORM 删除的重要特性:软删除实践案例(优化版)
  • 前端计算机视觉:使用 OpenCV.js 在浏览器中实现图像处理
  • React:利用React.memo和useCallback缓存弹窗组件
  • Oracle 常用函数
  • 设置linux静态IP