我们在引用API函数时需要先声明,比如引用GetWindowText时声明如下:
[DllImportAttribute("user32.dll", EntryPoint = "GetWindowText")]
public static extern int GetWindowText(IntPtr hwnd, StringBuilder lpString, int nMaxCount);
以上声明中EntryPoint表示函数入口点,如果不用EntryPoint将默认入口点为声明的函数名称,如:
[DllImportAttribute("user32.dll")]
public static extern int GetWindowText(IntPtr hwnd, StringBuilder lpString, int nMaxCount);
由于上面没有明确EntryPoint,函数名称GetWindowText将作为入口点,等同于加了EntryPoint = "GetWindowText"。
如果想个性化一点还可以使用非规范的函数名,这时候就一定要加EntryPoint指明入口点,如:
[DllImportAttribute("user32.dll", EntryPoint = "GetWindowText")]
public static extern int GetWinTitle(IntPtr hwnd, StringBuilder lpString, int nMaxCount);
另外,由于编码存在Unicode和 ANSI两种版本,API函数中有很多是区分了W跟A两个版本,GetWindowText也是有GetWindowTextA、GetWindowTextW两个版本,你也可以通过EntryPoint指定使用哪个版本,比如你想用GetWindowTextA版本,可像下面这样声明:
[DllImportAttribute("user32.dll", EntryPoint = "GetWindowTextA")]
public static extern int GetWindowText(IntPtr hwnd, StringBuilder lpString, int nMaxCount);
但这种存在两个版本的函数一般都定义了通用名称,像GetWindowText就是,所以在最前面的声明中没有明确哪个版本也没问题,GetWindowText在C++头文件中是这样定义的:
#ifdef UNICODE
#define GetWindowText GetWindowTextW
#else
#define GetWindowText GetWindowTextA
#endif // !UNICODE
如果用通用名称作为入口点,系统将根据编码情况自动调用合适的版本。所以,入口点名称建议使用通用名称。