Win32 API可以直接控制Microsoft Windows的核心,因为API(Application Programming Interface)本来就是微软留给我们直接控制Windows的接口。
Win32 API函数是放在Windows系统的核心库文件中的,这些库在硬盘里的存储形式是.dll文件。我们常用到的dll文件是user32.dll和kernel32.dll两个文件,还有其它一些dll文件也非常重要。
using System;
using System.Runtime.InteropServices;
class Program
{
[DllImport("User32.dll")]
public static extern int MessageBox(int h, string m, string c, int type);
static int Main()
{
MessageBox(0, "打招呼", "窗口名", 6);
Console.ReadLine();
return 0;
}
}
要使用DllImport这个特性(特性也是一种类),必须使用这一句using System.Runtime.InteropServices;
[DllImport("User32.dll")]是说我们要使用的Win32 API函数在User32.dll这个文件里。
int MessageBox( HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType );
函数名:MessageBox将保持不变。
返回值:int 将保持不变(无论是Win32还是C#,int都是32位整数)
修饰符:要求有相应的DllImport和public static extern
第一个:弹出的MessageBox的父窗口是谁。本例中没有,所以是0,也就是“空指针”。
第二个:MessageBox的内容。本例中是“打招呼”。
第三个:MessageBox的标题。本例中用的是“窗口名”。
第四个:MessageBox上的按钮是什么,如果是0,那就只有一个OK,MessageBox太短了,你将看不全“窗口名”三个字,于是我改成了6,这样就有三个按钮了。