Call the Windows API function (transfer) with Visual C #

zhaozj2021-02-16  130

??? API function is the cornerstone of building a WindWS application, each Windows application development tool, which provides the underlying function that is indirectly or directly calling the Windows API function, and in order to achieve functional expansion, it is generally provided. The interface of the WindowsAPI function, that is, the ability to call the dynamic connection library. 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: ?? Declaration of dynamic link library functions ?? Dynamic link library function must be declared before use, relative to VB, C # function declaration is more commendable, the former passes through the API Viewer It can be used directly, while 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, if you want to call the Messagebox function in user32.dll, we must specify the function's name MessageBoxa or MessageBoxwww, and library name user32.dll, we know that Win32 API is generally two A version of 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 calls: ?? [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 "#" before the number serial number. ?? Below is an example of replacing the MessageBox name with MSGBox: ?? [c #] ?? using system.runtime.interopservices; ?? public class win32 {?? [DLLIMPORT ("user32.dll", entrypoint = "messagebox")]? PUBLIC STATIC EXTERN INT MSGBOX (int hwnd, string text, string capen, uint type); ??} ?? Many jurisdictional link library functions expect you to deliver a complex parameter type to function, such as a user-defined Structure type members 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 Options ?? Description ?? Layoutkind.automatic ?? To improve efficiency to reorder type members. ?? Note: Never use this option to call unlicensed dynamic link library functions. ?? layoutkind.explicit ?? For each domain, in accordance with the fieldoffset property to sort the type members of the type member, the type member that appears in the undependedly of the jurisdiction, which appears in the jurisdiction of the jurisdiction. ?? Pass Structural members ?? The following example shows 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, and the function of the function is as follows: ?? Bool PtinRect (Const Rect * Lprc, Point PT);?? Note that 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 rest {?? [fieldoffset (0)] public int in [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); ??} ?? Similar to you can call the getSystemInfo function to get system information: ??? 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 class members is the same as 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.dll's getSystemTime function, function C / C call specification is as follows:?

Void getSystemTime (SystemTime * SystemTime); ; ?? public ushort wMonth; ?? public ushort wDayOfWeek; ?? public ushort wDay; ?? public ushort wHour; ?? public ushort wMinute; ?? public ushort wSecond; ?? public ushort wMilliseconds; ??} ?? class Win32API {?? ["User32.dll"] ?? public static extern void getSystemTime (mysystemtime st); ??} ?? Tune function delivery: ?? From the jurisded code, most dynamic link library functions You only need to create a definition of the jurisdiction, 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 Create a callback function in the jurisdiction; 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, for example, for enumeration functions, such as EnumFontFamilies in Win32 API, enumprinters, EnumWindows, EnumWindows (window enumeration) Function. Below the window enumeration as an example, talk about how to traverse all windows existing in the system by calling the EnumWindow function, divide a few steps below: ?? 1. Declaration of the first reference function before the call ?? Bool EnumWindows (WndenumProc LPENUMFUNC, LPARMAM iParam) ?? Obviously this function requires a callback function address as a parameter. There are 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, the platform automatically converts the representative to the functionality 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 enjoyWindows (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 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, we can sometimes use array to deliver parameters. . ?

Below this function gets the username "?? lptstr lpbuffer, // username buffer size address pointer by calling getUsername); ?? ?? [DLLIMPORT (" advapi32.dll ", ?? EntryPoint =" GetComputerName ", ?? ExactSpelling = false, ?? SetLastError = true)] ?? static extern bool GetComputerName (?? [MarshalAs (UnmanagedType.LPArray)] byte [] lpBuffer, ?? [Marshalas (unmanagedType.lparray] INT32 [] nsize); ?? This function accepts two parameters, char * and int *, because you must allocate a string buffer to accept string pointers, you can use String class instead This parameter type, of course, you can also declare a byte array to pass ansi string, and you can also declare a long integer array with only one element, 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.Encoding.ascii.getstring (str)); ?? Finally, it is necessary to remind that each method must be in the file header before use: ?? using system.Runtime.InterOpServices; ??

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

New Post(0)