API functions are the cornerstone of building windows and an essential tool for Windows programming. Every windows application development tool provides an indirect or direct way to call WIN32API, and C # is no exception. One advantage of using WIN32API is that we can implement more functions.
First, introduce the namespace: using system. runtime. interopservices;
Then, declare the API functions used in the program. Note that the method body is empty.
The dllimport attribute is used to specify the DLL location that contains the implementation of an external method.
(1) The dllimport attribute can only be placed on the method declaration.
(2) dllimport has a single positioning parameter: Specify the dllname parameter that contains the DLL name of the imported method.
(3) dllimport has six naming parameters:
A. callingconvention parameter: indicates the call convention of the entry point. If callingconvention is not specified, the default value callingconvention. winapi is used;
B. charset parameter: indicates the character set used in the entry point. If charset is not specified, use the default charset. Auto;
C. entrypoint parameter: name of the declared method entry point in DLL. If entrypoint is not specified, use the method name;
D. exactspelling parameter: indicates whether the entrypoint must exactly match the spelling of the indicated entry point. If exactspelling is not specified, use the default value false;
E. preservesig parameter: indicates whether the method signature should be retained or converted. When the signature is converted, it is converted to an additional output parameter signature named retval with the hresult return value and the return value. If preservesig is not specified, the default value false is used;
F. setlasterror: indicates whether the methods retain Win32 errors. If setlasterror is not specified, the default value false is used.
Dllimport is a one-time attribute class, and the method modified with dllimport must have an extern modifier.
Example: [dllimport ("Kernel32")]
Private Static extern void getwindowsdirectory (stringbuilder WINDIR, int count );
[Dllimport ("user32.dll", entrypoint = "flashwindow")]
Private Static extern bool flashwindow (intptr hwnd, bool binvert );
[Dllimport ("ws2_32.dll")]
Private Static extern int inet_addr (string CP );
[Dllimport ("iphlpapi. dll")]
Private Static extern int sendarp (int32 destip, int32 srcip, ref int64 pmacaddr, ref int32 phyaddrlen );
Explanation of dllimport attributes