天天看点

P/Invoke使用Win32非托管函数

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);
            }

        }
    }
}
           
c#