The API function is the cornerstone of the WindWS application, each Windows application development tool, which provides the underlying function that is indirectly or directly calls the Windows API function, and in order to implement functional extensions, it is generally provided to call the WindowsAPI function. Interface, that is, the ability to call dynamic connection libraries. Visual C # and other development tools can also call the dynamic link library API function. The .NET framework itself provides such a service that allows the code-up code to call the Dynamic Link Library, which includes the Windows API function provided by the operating system. It is capable of positioning and calling the output function, organizes each parameter (integer, string type, array, and structure, etc.) as needed, across the interoperability boundary.
The following is a basic process of calling the API as an example: Dynamic Link Library functions must be declared before the dynamic link library function is used, relative to VB, C # function declaration is more commendable, after passing by API Viewer, you can use it directly And the latter needs to do additional changes in parameters.
Dynamic Link Library Function Declaration Sections are generally composed of two parts of the following, one is a function name or an index number, and the other is the file name of the dynamic link library. For example, you want to call the Messagebox function in user32.dll, we must specify the name MessageBoxa or MessageBoxwwwa or MessageBoxwww, and library name user32.dll, we know that Win32 API has two versions of each of the functions involving strings and characters. The ANSI version of the single-byte character and the Unicode version of the double-byte character.
Here is an example of the API function call: [DllImport ( "KERNEL32.DLL", EntryPoint = "MoveFileW", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool MoveFile String SRC, STRING DST;
Where the entry point EntryPoint identification function is in the entry location of the dynamic link library, in an jurisded engineering, the original name and serial number entry point of the target function not only identifies a function of the interoperability boundary. Moreover, you can also map this entry point into a different name, that is, rename the function. Rename can bring all kinds of convenience to the call function, by renaming, on the one hand, we don't have to write to the function of the function, and it can also ensure consistent with the existing naming rules, allowing a function with different parameter types. Coexistence, more importantly, it simplifies the call to ANSI and Unicode versions. Charset is used to identify function calls, which is Unicode or ANSI version. Exactspelling = false will tell the compiler to make the compiler decide to use Unicode or ANSI version. For other parameters, please refer to MSDN online help.
In C #, you can declare a dynamic link library function through the name and serial number in the EntryPoint field, if the function name used in the method definition is the same as the DLL entry point, you don't need to display the declaration function in the EntryPoint domain. Otherwise, you must use the following attribute format to indicate a name and serial number.
[DLLIMPORT ("Dllname", entrypoint = "functionName")] [DLLIMPORT ("Dllname", entrypoint = "# 123")] It is worth noting that you must add "#" in front of the digital serial number to replace it with MSGBOX examples MessageBox name: [C #] using System.Runtime.InteropServices; public class Win32 {[DllImport ( "user32.dll", EntryPoint = "MessageBox")] public static extern int MsgBox (int hWnd, String text, String caption, UINT TYPE);} Many jurisdictions of dynamic link library functions expect you to deliver a complex parameter type to function, such as a user-defined structural type member or a class member defined by the jurisdiction, and you must provide additional Information formatted this type to maintain the original layout and alignment of the parameters.
C # provides a StructLayOutAttribute class, which you can define your own formatted type. In the jurisdiction code, the formatting type is a structure or class member with StructLayOutAttribute, which guarantees its internal member expected layout information. There are three options in the layout:
LayoutKind.automatic LayoutKind.automatic In order to improve efficiency allows the run state to reorder type members. Note: Never use this option to call unlicensed dynamic link library functions. LayoutKind.ExPlicit Sorting LayoutKind.SEQUENTIAL on the type member in the Fieldoffset property, LayoutKind.SEQUENTIAL is sorted by a type member that appears in the jurisdiction from the jurisdiction of the jurisdiction. The following examples below describe how to define a point and rectangle type in the jurisdiction and pass it to the PtinRect function in the user32.dll library as a parameter, the unlicensed prototype statement is as follows: BOOL PTIECT (Const Rect * LPRC, POINT PT); Note You must pass the Rect structural parameters by reference, because the function requires a RECT structure pointer. [C #] using system.runtime.interopservices;
[Structlayout (layoutkind.sequential)] public struct points {public int x; public int y;}
[StructLayout (LayoutKind.Explicit] public struct Rect {[FieldOffset (0)] public int left; [FieldOffset (4)] public int top; [FieldOffset (8)] public int right; [FieldOffset (12)] public int bottom }
class Win32API {[DllImport ( "User32.dll")] public static extern Bool PtInRect (ref Rect r, Point p);} Similarly GetSystemInfo you can call the function information obtaining system: using System.Runtime.InteropServices; [StructLayout (LayoutKind. Sequential)] public struct SYSTEM_INFO {public uint dwOemId; public uint dwPageSize; public uint lpMinimumApplicationAddress; public uint lpMaximumApplicationAddress; public uint dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; public uint dwAllocationGranularity; public uint dwProcessorLevel; public uint dwProcessorRevision;} [DllImport ("kernel32")] static extern void getSysteminfo (Ref system_info psi);
System_info psi = new system_info (); getSystemInfo (Ref psi);
The passage of a member is also as long as the class has a fixed class member layout, you can also pass a class member to a dynamic link library function that is not jurisdiction. The following example mainly shows how to pass a Sequential order definition MYSystemTime class to USER32. The DLL's getSystemTime function, the function of the function of the C / C is as follows:
void GetSystemTime (SYSTEMTIME * SystemTime); not passed value type, class is always passed by reference [C #] [StructLayout (LayoutKind.Sequential)] public class MySystemTime {public ushort wYear;. public ushort wMonth; public ushort wDayOfWeek; public ushort wDay; public ushort wHour; public ushort wMinute; public ushort wSecond; public ushort wMilliseconds;} class Win32API {[DllImport ( "User32.dll")] public static extern void GetSystemTime (MySystemTime st);} callback functions of: from Most dynamic link library functions are called in the jurisdiction, you only need to create a definition of the jurisdiction, and then call it, this process is very straightforward. If a dynamic link library function requires a function pointer as a parameter, you still need to do the following steps: First, you must refer to the documentation about this function, determine if this function needs a callback; second, you must be in the jurisdiction code Create a callback function; Finally, you can deliver a pointer to this function to the DLL function,.
The callback function and its implementation: The callback function is often used in the task needs to be repeatedly executed, such as enumeration functions, such as EnumFontFamilies in the Win32 API, Enumprinters, EnumWindows (Window Enumeration) functions. The following is a window enumeration as an example, talking about how all the windows existing in the ENUMWINDOW function traversal system: 1. Declaration of the reference function before the call, Bool EnumWindows (WndenumProc Lpenumfunc, LParmam iParam) apparently The function requires a callback function address as a parameter. 2. Create a callback function under the jurisdiction, this example is declared as a representative type (DELEGATE), which is what we call, it has two parameters hWnd and LParam, the first one The parameter is a window handle, the second parameter is defined by the application, both of which are shaped.
When this callback function returns a non-zero value, the indication is successful, and the ridge is hints, this example always returns the TRUE value for continuous enumeration. 3. Finally, create a representative object, and passed it as a parameter to the EnumWindows function, and the platform automatically converts the transformation into a function that can identify the callback format that can be identified.
[C #] using system.Runtime.Interopservices;
Public Delegate Bool Callback (int hwnd, int lparam);
Public class enumreportapp {
[DLLIMPORT ("User32")] Public Static Extern Int EnumWindows (Callback X, INT Y);
Public static void main () {callback mycallback = new callback (enumreportapp.report); Enumwindows (MyCallback, 0);}
Public Static Bool Report (int hwnd, int lparam) {console.write ("window handle is"); console.writeLine (hwnd); return true;}}
Pointer type Parameter Pass: When the Windows API function is called, most of the functions use pointer to pass parameters, for a structural variable pointer, in addition to using the above class and structural methods, we can sometimes use array to pass parameters.
Below this function gets the username Bool getUserName (LPTSTR LPBUFFER, // username buffer LPTWORD NSIZE //); [DLLIMPI32.DLL ", entrypoint =" getcomputername ", EXACTSPELING = false, SetLastError = true)] static extern bool GetComputerName ([MarshalAs (UnmanagedType.LPArray)] byte [] lpBuffer, [MarshalAs (UnmanagedType.LPArray)] Int32 [] nSize); this function takes two parameters, char * and INT *, because you must allocate a string buffer to accept string pointers, you can use String classes instead of this parameter type, of course, you can also declare a byte array to pass ansi string, and you can also declare a only one Long integer array of elements, using an array name as the second parameter. The above functions can be called as follows: byte [] str = new byte [20]; int32 [] len = new int32 [1]; len [0] = 20; getcomputername (str, len); messagebox.show (system.text); messagebox.show .Encoding.ascii.getstring (STR)); Finally, it is necessary to remind that each method must be in the file header before use: use system.Runtime.InterOpServices;