. NET platform calls Win32 API

Source: Internet
Author: User
Thanks to the spirit of serving the people from the original author and give me a gift!

Author: Liu tiemeng
Date: 2005-12-20
Keyword: C #. NET Win32 API

Copyright Disclaimer: This article is protected by intellectual property law. If you want to reprint it, Please repost it together with your name and send a Mail to the bladey@tom.com, I 'd like to know where my articles are. thank you.

 

Small order
Win32 API can directly control the core of Microsoft Windows, because Application Programming Interface is the Interface that Microsoft left for us to directly control Windows. Want to play? It's too difficult.
C # it is very simple to use. Writing a program is like playing gongshu, Sorry -_-! It is as simple as building blocks. Want to play? Haha, there is no way to directly control the core of Windows.
Is there no perfect solution? Of course not! Otherwise, no one has bought Microsoft products. In fact, calling Win32 APIs from C # (or. NET platform) is still very simple ~~~~ Today, we will study it together.

I. Basic Knowledge
Win32 API is a function set of C language (note that C ++ is not a language, although C is a subset of C ++.C # The language is completely different from the C Language(In addition to syntactically similar). Therefore, it takes some time to call the Win32 API of C language in C. First, we need to prepare some basic knowledge.
1. Where can Win32 API functions be stored?
Win32 API functions are the core of Windows. For example, the forms, buttons, and dialogs we see depend on Win32 functions to draw on the screen. These controls (sometimes called components) these functions are used for User interaction with Windows. Therefore, the Win32 API functions used to control these controls are called "User Interface Win32 APIs" (UI functions for short). There are also some functions, it is not used for interaction, such as managing processes running in the current system and monitoring the status of the hardware system ...... These functions have only one set, but can be called by all Windows programs (as long as the program has high permissions). In short, APIs are shared by the program. To enable all programs to share a set of APIS, Windows adopts the "Dynamic Link Library" approach. The reason for calling "Dynamic Link Library" is that the function library is called in a "pay-as-you-go" way, rather than a "don't need to be used" like a static Link Library ".
This is not easy to understand. It doesn't matter. Let's give a small example. We compared Windows to a playground, and compared children playing in the playground to a program. A child may need to drink water while playing. We have two ways for the little guys to drink water: 1. provide each of the little guys with a kettle. If the little guys drink, they will drink the water they bring. 2. assign a water dispenser to the playground. Obviously, the second method is much better, which is reflected in three places.FirstWith a bottle, the little guy is not flexible and has a bad time (affecting the speed of the Program). Besides, this is just a bottle. What if I bring another lunch box? Slide, helmet, Band-Aid, gauze ...... AK-47 My God, if it's all, it's time to catch up with the US Army. So there is still a public "warehouse" in the amusement park for convenience, so that everyone can use it as needed (dynamic link ).SecondThe little guys brought so many things and occupied many places in the playground, so that the playground was crowded and other children could not enter (the large size of the program affects the performance of the program and system ).ThirdIf an item has been upgraded, for example, the kettle has been changed from 1 to 2, then each of the little guys must go home to change to a new one (re-compile the program, the compiler links the new static library to the main body of the Program). In the second case, as long as the playground changes the model of the kettle in its own warehouse, then all the little guys have a large kettle at the same time. (Wukong! I'm not here for a while. Why are you losing something ?! It's not good to hit the kids ~~~~~)
Wukong is in a hurry, so I will not be confused ...... Er ...... Win32 API functions are stored in the core library files of the Windows system. These libraries are stored in the hard disk as. dll files. The commonly used dll file isUser32.dllAndKernel32.dllTwo files, and some other dll files are also very important. You need to accumulate more experience in practice.
We know that Win32 API functions are stored in the dll file, but the new problem comes again-how can we call them? These dll files are written in C language. After the source code is compiled by the C language compiler, the files are stored in binary executable code, it's like an apple is packed in a jar after it is made into jam by a shredder-you can no longer tell which one is from your GF and which one is from your mom. To allow the program to use these functions, Microsoft also releases the system SDK when releasing each new operating system. Currently, the latest SDK is Win2003 SP1, it is said that Vista is coming soon, And the UI APIs have been separated from the core library to improve system stability. The SDK contains some C header files (. these files describe the Win32 API functions in the core dll files. # include "..... "commands are included in your program, and you can use these Win32 APIs. As for how the program is linked, it is beyond the scope of this article-and beyond my knowledge: D
Now, if you are a C language expert, you can use the Windows SDK to transfer Windows! However, today we are talking about calling the Win32 API in the C # language. Now we know that the API functions are stored in the dll dynamic link library file and how the C language calls them. What should we do with the C # language? C # language does not support C. H files. C # language also uses dll dynamic link library, but these dll are. NET version, with "self-descriptive", that is, all functions in your stomach have been written in your metadata, and no additional one is needed. h file. Now we have found the key point of the problem: how to use the C # language on the. NET platform to call the dll files on the Win32 platform.The answer is very simple: Use the DllImport feature.
Ii. Test the knife
Next, let's write a small program and try to use the C # language and the DllImport feature to call Win32 API.

Using System;
Using System. Runtime. InteropServices;
Class Program
{
[DllImport ("User32.dll")]
Public static extern int MessageBox (int h, string m, string c, int type );

Static int Main ()
{
MessageBox (0, "Hello Win32 API", "Essence of water", 4 );
Console. ReadLine ();
Return 0;
}
}

Create a C # console program, clear the code automatically generated by VS, and Copy the code above to compile and execute it. Let's analyze this program:
1. To use the DllImport feature (the feature is also a type), you must use this using System. Runtime. InteropServices;
, Import "RunTime-> interactive service ". Oh ~~~~ Isn't the interactive service at runtime a "Dynamic Link? Thanks to Microsoft!
2. Then we can create a DllImport class instance and bind the instance to the function we want to use. "Feature class" is a very strange type-MyClass mc = new MyClass () is not used for manufacturing class instances. Instead[Feature class (parameter list)]In this form, feature classes cannot exist independently and must be used to modify other objects (in this example, a function is modified later). Different features can be used to modify classes, functions, variables, and so on; when a feature instance is compiled, it does not generate executable code, but is put into metadata for retrieval. In short, you remember that the feature class is very strange. If you want to know more, you can check MSDN. If you are too lazy to check it, remember this first-understanding the law of inertia does not affect your learning to ride a bicycle. [DllImport ("User32.dll")] indicates that the Win32 API function we want to use is in the User32.dll file. The problem comes again: How do I know which dll file Many API functions are in? You can find this in MSDN. The location isRoot-> Win32 and COM Development-> Development Guides-> Windows API Reference-> Functions by Category. On this page, you will see a lot of API categories, all of which are here. Open a category, such as Dialog Box,In the Functions Section, You will see a lot of specific functions, including the MessageBox function used above, click to enter. You will open the detailed explanation and usage of MessageBox. Its name, return value, and parameter type have a full view! I am also very familiar with English ~~~~ At the bottom of this page, you can see a small table with a "Minimum DLL Version user32.dll", which means this function is in user32.dll.
3. The next step is our function. There are several key points for calling Win32 functions in C.First: The name must be exactly the same as that of the Win32 API.Second: In addition to the DllImport class modification, the function must be declared as public static extern.Third: This is also the most abnormal point. The return value and parameter type of the function must be exactly the same as that of the Win32 API! This is hard for this group of beginners-the Win32 Data Type is quite strange, such as what LPSTR and what HINSTANCE are all Xiami Dongdong? For your reference, my Blog shows "exploring Windows data types-who are you?" For more information, see. In addition, I have extracted a table from MSDN, which corresponds to the common Win32 Data Types and. NET platform data types:
Figure 2 Non-Pointer Data Types

Win32 Types Specification CLR Type
Char, INT8, SBYTE, CHAR 8-bit signed integer System. SByte
Short, short int, INT16, SHORT 16-bit signed integer System. Int16
Int, long, long int, INT32, LONG32, BOOL, INT 32-bit signed integer System. Int32
_ Int64, INT64, LONGLONG 64-bit signed integer System. Int64
Unsigned char, UINT8, UCHAR, BYTE 8-bit unsigned integer System. Byte
Unsigned short, UINT16, USHORT, WORD, ATOM, WCHAR, _ wchar_t 16-bit unsigned integer System. UInt16
Unsigned, unsigned int, UINT32, ULONG32, DWORD32, ULONG, DWORD, UINT 32-bit unsigned integer System. UInt32
Unsigned _ int64, UINT64, DWORDLONG, ULONGLONG 64-bit unsigned integer System. UInt64
Float, FLOAT Single-precision floating point System. Single
Double, long double, DOUBLE Double-precision floating point System. Double
In Win32 this type is an integer with a specially assigned meaning; in contrast, the CLR provides a specific type specified Ted to this meaning.

With these things, we can convert a Win32 API function into a C # function. Take the MessageBox function as an example (see the function table just given). Its Win32 prototype is as follows:

IntMessageBox(HWNDHWnd, LPCTSTRLpText, LPCTSTRLpCaption, UINTUType);

Function Name: MessageBox will remain unchanged.
Return Value: Int will remain unchanged (whether Win32 or C #, int Is a 32-bit integer)
Parameter table: H indicates Handle. Generally, Handld is pointer type. The pointer type of Win32 platform is stored in 32 bits, so it corresponds to an int integer in C. However, since it is a pointer, there are no positive and negative points, and 32 bits should be used to save the value -- in this way, uint (unsigned 32-bit integer) is used) to correspond to the H type of Win32. However, int is subject to C # And. net clr, and uint is only supported by C. net clr support, so the int type is used honestly in this example. (Ele. Me ...... Stick to it ......)
As for the abbreviation of Long Pointer to Constant String, it is a String. Therefore, the string type in C # is correct.
Modifier: The corresponding DllImport and public static extern are required.

After some tossing, the Win32 MessageBox function is packaged into a C # function that can be called:

[DllImport ("User32.dll")]
Public static extern int MessageBox (int h, string m, string c, int type );

Let me explain the usefulness of the four parameters:
First: Who is the parent window of the pop-up MessageBox. This example does not exist, so it is 0, that is, "Null Pointer ".
Second: MessageBox content. In this example, it is "Hello Win32 API ".
Third: The title of MessageBox. In this example, the name of my Blog-the true meaning of Water-should be forgotten.
Fourth: What is the button on MessageBox? If it is 0, there will be only one OK. MessageBox is too short. You will not be able to see the four words "the true meaning of water", so I changed it to 4, so there are two buttons. These are available in MSDN function usage. However, I recommend that you read another notebookEvolution of A Win32 Program.
So far, although a sparrow is small, it has been poisoned ~~~ Sorry -_-! The program that calls Win32 API is analyzed. The principle is not difficult! It's enough for fresh graduates to win HR! The true knowledge is that you are proficient in using MSDN, SDK,. NET Framework class library VC/VC. Believe me -- MSDN + SDK + VC/C # is definitely enough to pack Windows properly.
3. Is it really necessary?
Hey hey ...... Look at my face. I'm smiling! You are all fooled! Not all underlying Windows operating systems must call Win32 APIs ~~~~ (Where are the bricks !!!)
What I want to say is:. NET Framework is a good encapsulation of Win32 APIs. Most Win32 API functions have been encapsulated in various classes of. NET Framework class libraries. If Win32 API functions are pearls scattered on the ground. NET Framework is to split these pearls into various drawers by type-remind me of my mom-I can always find them when my books are full of beds, as soon as she packed up, I couldn't find it again, so she was depressed. Alas ...... No way. Let's take a closer look at the. NET Framework class library. There will be a lot of surprises!
Finally, let's end our article with an example!
The example is as follows ~~~~~
A long time ago, I wrote a program for a company to control user logon. Before logon, the user cannot move the mouse out of the logon form because the mouse must be controlled, so I first remembered calling the Cursor-related functions in the Win32 API-so no matter how many calls were made to the ClipCursor () function in the Win32 API, the effect was good.
When I flipped through the. NET Framework class library two days ago, I found that the Clip attribute of the System. Windows. Forms. Cursor class is dedicated for this purpose! I almost lost my nose ...... Create a C # Windows program by yourself, paste the following core code to the double-click event of the main form, and try it. The purpose of this example is to tell you:1. The program for understanding the class library directly determines the efficiency and quality of your programming-using the components in the class library is much faster and safer than what we create from the wheel. 2. Do not directly call Win32 API functions-that is not safe.

Private void Form1_DoubleClick (object sender, EventArgs e)
{
Rectangle r = new Rectangle (this. Left, this. Top, this. Width, this. Height );
System. Windows. Forms. Cursor. Clip = r;
}

Finally, you must be very curious about which Win32 APIs are encapsulated by the. NET Framework. Okay, and an article in MSDN specifically lists these. The article is named Microsoft Win32 to Microsoft. NET Framework API Map. Read this article by yourself.
4. Gratitude
The New Year is approaching, and this article is also a small gift. One is the joy of the family, and the other is to let us always remember this happy moment.
Send it to the Lu manager who has knowledge of me;
I sent Liu yinglead a thank-you for your guidance and support;
I have sent my Team partners lelian and Wang Yong (Worksoft). Without your help, it is impossible for me to start my work!
I gave it to my dormitory brother Zhang Xiong. Without you, I may want to sleep at the metro station.
To Duan Wei and Chen Ning, thank you for organizing the activities and training.
To Chen Xi, Chen Jian, Wang Yong, Chang Yong, Shun Xian, Ting, opposite Girl Li Fang, JJMM in this group, and Xiao Zhu ...... Working with you is my greatest pleasure!

Write an article ~~~~ Qingcheng MM also probably prepared rice for the bird ~~~~ Home bird ~~~~

Copyright Disclaimer: This article is protected by intellectual property law. If you want to reprint it, Please repost it together with your name and send a Mail to the bladey@tom.com, I 'd like to know where my articles are. thank you.

You need to paste it back. If you do not paste it back, please be careful when using a slingshot to hit your glass !!!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.