Call the Windows API function with Visual C #

xiaoxiao2021-03-05  49

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 position 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 at 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 be in the EntryPoint domain Display declaration function. 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 for the layout: layout option Description 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 Point {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 the class member is also as long as the class has a fixed class member layout, you can also pass a class member to an unlicensed dynamic link library function, the following example mainly explains how to pass A Sequential order defined mysystemTIME class to the getSystemTime function of user32.dll, the function of the C / C call specification is as follows: void getSystemTime; unlike the value type, the class is always passed through the 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);} Passage of callback function: Calling most dynamic link library functions from the jurisded code, you only need to create a derived function definition, and then call It can be, 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 as a parameter to the DLL function, callback function and its implementation: The callback function is often used in the task needs to be repeated, such as for enumeration functions, For example, EnumFontFamilies (font enumeration), enumprinters, enumwindows (printers), enumerations below as an example below, talk about how to divide all windows existing in the system by calling the EnumWindow function Steps: 1. Declaration Bool EnumWindows (WndenumProc LpenumFunc, LParmam iParam) before the call, clear this function requires a callback function address as a parameter. 2. Create an jurisded callback function, this example declares as a representative type (delegate), that is, what we call, with two parameters hWnd and lparam, the first 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; 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"); Console .Writeline (hwnd); Return True;}} pointer type parameter passed: 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 and structural methods to pass parameters We can sometimes use arrays to deliver parameters.

转载请注明原文地址:https://www.9cbs.com/read-32956.html

New Post(0)