using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
//System.Runtime.InteropServices 命名空间提供各种各样支持 COM interop 及平台调用服务的成员。
namespace Win32API
{
class Program
{
[DllImport("user32.dll")] //导入user32.dll里面的所有的API函数(MessageBox()由这里导入);
public static extern int MessageBox(int hwnd,
string text, string caption, uint type);
//在这里定义MessageBox()API函数
//extern 修饰符用于声明在外部实现的方法。
//extern 修饰符的常见用法是在使用 Interop 服务调入非托管代码时与 DllImport 特性一起使用。
//在这种情况下,还必须将方法声明为 static
const uint MB_OK = 0; //定义API常数
const uint MB_OKCANCEL = 1;
const int IDOK = 1;
static void Main(string[] args)
{
Program.MessageBox(0, "OnYaeh!", "win32API", MB_OK); //直接调用MessageBox()静态方法
if (MessageBox(0,"点击下Ok","Ok",MB_OKCANCEL)==IDOK)
{
MessageBox(0, "你点击了Ok", "Ok", MB_OK);
}
else
{
MessageBox(0, "你点击了取消", "Cancel", MB_OK);
}
}
}
}
P/Invoke使用Win32非托管函数
最新推荐文章于 2025-07-02 09:58:28 发布
本文介绍如何在C#中通过DllImport导入user32.dll,并使用MessageBox函数显示消息框。示例展示了如何定义API函数及常量,并通过调用静态方法实现消息对话框的不同交互。
754

被折叠的 条评论
为什么被折叠?



