Source to http://www.d2school.com
The first article sees through Windows "Through Windows" preface, finally started Windows programming. We are also unavoidable, starting with Windows. Remember in "Valley C ", we tried to re-recognize what computers with "programmers", think everything in the computer is 0 and 1. Now, more arduous tasks are in front of us. The content of some chapters before this course is: seeing through Windows. (Don't lift with me, saying that Windows is so complicated, how can you see, you understand that our task is mainly trying to see the Windows operating system from the perspective of the program.) From Windows 3.1 to Windows 95, 98, ME, And today's Windows XP, there are Windows NT, Windows 2000. Windows This operating system has long been spread over the world's various corners. So you should be unfamiliar with Windows. But you are not a programmer, or not "Windows programmer". So, what you see, must be seen with me, not the same. When I switched my identity, I was like a lot of people, I have been windows, and it's too big, the speed is too slow, it is easy to crash, very unsafe. And when I realized that I was a programmer, I closed. I can guarantee that learning all "see Windows", you are a standard "Windows" programmer - because you can write multiple real Windows programs. And these programs are all directions that direct Windows world. When you arrive, you will also me, understand that "Windows can be written for a day." Thus no longer complains about Windows. Of course, our identity is double, you can always switch your own identity to "end users", and then combine the procedures you have learned, get up in Windows. Moreover, in fact, I am also very happy to teach these: d You look at this picture, we will write such a program: (Figure 1: Playing a big fork on the Windows desktop) Want to deny the value of Windows? One of the most intuitive and no malicious practices is to play a red fork on its desktop. For the words, what do we want to see from Windows? The primary task is: 1, the GRAPHIC USER INTERFACE Drawing Data User Interface Before we use, we use the DOS operating system. When learning "Vernacular C ", I have been dealing with that black window. Look at the windowsxp gorgeous appearance, then look at the DOS window. WINDOWS is Windows, the most foundation is that it provides users with a graphic world. Everything you see now, the start button, the "My Computer" icon on the desktop, and all text, graphics, they all draw. The Windows generation is better than one generation, but it is to make me feel comfortable. Windows is a GUI operating system. 2, the API (Application Programming Interface Application Program) GUI is to see a normal computer user. And this API is only prepared for Windows programmers. Through the graphical interface, the end user can manipulate the mouse or press the keyboard to operate through the hand, control Windows, such as the "Start" button, then select the shutdown menu item to turn the computer.
But what should I do if I want to shut down through the program? Then you need API. The API is the program to "see" to "interface." In addition, the user can drag a file to the "recycle bin", the program can also "drag" a file to "Recycle Bin". It's just the former through the GUI, while the latter passes the API. Yes, have you encountered the default homepage of IE and the window title is changed? Those experience articles teach us how to recover through the registry editor, and then emphasize: Be careful, don't make mistakes ..., for a programmer, the hate of the manual change the registry is no longer in it. Danger, but it's trouble, tired of your eyes! Ok, the program is doing, how do the program do? Use the API. The programmer controls Windows through the API. 3, Messages Loop GUI and API look so different. It seems that one is a wooden bridge that walks the sun. Although not all, in many places, both are actually close. On a busy road deep in Windows, "characters" from Gui and people from "API" may take a place before! Then, "Message Cycling" is said. The "cycle" here is not to say that a message must be "around a circle"; but said that thousands of messages are in the "message channel" established by Windows, and finally Going to your respective destination ... If you are "from", the thickening point is: the message can come from the program or from the user. Do you understand "news"? Third Chapters of "Vealand C " have been talked about the information of human hand moving. This information is finally packaged into a "message", sending Windows, telling Windows: "The user doubles the 'My Computer'. The news produced by the peripherals such as the mouse and keyboard is just a small part of the Windows message. More messages are for programmers, leave them to the program. I don't want to do such a naughty program: I want to double-click the "My Computer" of your colleagues, "My Computer" window is just turned off! He doubles! Double click! ! Double click! ! ! It is not to open "his computer." Finally, you will have to kill you. "Doing this" before the April Fool's Day. Before the start of this department, I assume that you have learned C . If not, you should learn "Valley C " first. In addition, you should have a little English foundation, which helps to understand the functionality of the code from the most basic level of the name of the number of variables in the program code. The first chapter of the world of GUI (1) Everything is drawn 1.1 "Everything is" Windows ", Chinese translation into" Window ". Why is the "window"? Maybe you know, Microsoft calls it as a "window": (Figure 2: A "windows") above is the window I double-click "My Computer", the window. Not only Windows comes with, such as "Resource Manager", or "IE" and other applications with "Windows", all procedures running on Windows unless it does not need any operable interface, otherwise, It must at least one window (called the main window). For example, our common QQ: (Figure 3: Your QQ may be beautiful, but also the window) not only this variable size window is called a window, but some dialog is fixed, but it is also called a window on the program.
Not only big, the window with content is a window, a small button, also known as "window" on the program. Where is these windows? These windows are drawn from Windows. Let's take a small button to see. In order to see more clearly, I set the web position background of the button to red. (Figure 4: One Start button is also a window) button has 3 dimensional effects. In fact, it is painted. A rectangle, left, and painted a white edge; and the outermost layer is a black line, the inner layer is a gray line. The surface of the button is silver. This constitutes a stereoscopic effect (if you do not believe, you can try it in the drawing program). The window is drawn. The three-dimensional effect of such a small button will have to draw at least 6 lines. What about a very complicated window? More terrible, all portraits, text, lines in the window, even if it is filled into a blank, all the effects of painting. Some people may have to give up: Learning programming, not only learning logic, English, did not expect to paint? Everything is of course not so bad! The facts let this, the Windows operating system will help us paint (but in the DOS era). However, if it is handed over to the operating system, then the writing program seems to have any meaning? Therefore, the operating system still provides an interface to make the programmer when it is considered appropriate, and draws the right place when it is considered appropriate. 1.2 First Program: Take Windows Big Red Flies! Of course, "Suitable is not suitable", Windows is not too tube. Also can't. So, our first program is: Draw a big fork on a Windows desktop. If Billk is visible, he may think that we are doing so uncomfortable. How do you appear on the screen? I just asked here, a female student said: "It is not too difficult." She is right! This is the credit of C Builder. Originally, everything must be deald through the API mentioned earlier. However, CB has made a good package for related these APIs, making us can do with extremely natural (object-oriented), short program code. (I finished these, put the eyes of the praise to that female student, but found that she had already taken an exit red, rapidly playing a fork on the screen). Run C Builder 6, Menu: File | New | Appication. CB6 is a new blank Windows program engineering. And a form (FORM) is automatically generated. We know that this form is called window (Window) after the program runs. (If you are not familiar with these and some CB related operations, please review the Chapter 2 of "Vernacular C "). Take this table, then select the Button (buttons) from the "Standard" page of the control bar, put it on the form. The effect should now be as follows: Double-click the button placed on the form. The code editing window appears.
There should be these contents in the current code: void __fastcall tform1 :: button1click (TOBJECT * Sender) {} Fill in the following content between a pair of {}: (the line number does not type!) // get the length of the screen first : 1) int ScreenWidth = Screen-> width; 2) int ScreenHeight = Screen-> Height; 3) HDC HDC = :: getDC (0); // Get "Canvas" 4) Tcanvas * Screencanvas = New Tcanvas ; 5) Screencanvas-> Handle = HDC; // Set the canvas brush (PEN) 6) Screencanvas-> Pen-> color = CLRED; / / The color of the brush is red (Red) 7) Screencanvas-> Pen-> Width = 10; // The thickness of the brush // starts the fork, you need to draw two strokes, this is the first: left to the right 8) Screencanvas-> Moveto (0, 0); // Move the brush to (Move) To) Coordinate 0,0, that is, the top left upper corner of the screen 9) Screencanvas-> LineTo (ScreenWidth, ScreenHheight); // draw a line from the current location (line to) to the lower right corner of the screen. // Second: Right to the left: 10) Screencanvas-> MoveTo (ScreenWidth, 0); 11) Screencanvas-> Lineto (0, ScreenHeight); // Release "Canvas: 12) Screencanvas-> Handle = 0; 13) Delete screencanvas; 14) :: ReleaseDC (0, HDC); Save Project. Compilation: Ctrl F9. If an error is reported, you indicate that your code is incorrect. Run: f9. The window appeared. There is a button above. If your CB6 is displaying, minimize it to expose the Windows desktop. Then, click the button. The picture effect of the front picture of this chapter should come out. I do not know what you're thinking? But I want to tell you through this procedure: You are in the faced Windows, all of which use Windows, and everything is drawn. Ordinary users have no "power" to participate in this work. But the programmer has the right to participate - only us seem to be destroyed. Code Interpretation: We don't want to talk to too many technical details and achieve principles in the chapter of "seeing". But fortunately, the above code is natural. If you don't know what is called "class", then you need to continue learning "Valley C ". The above is used in two classes: Tscreen and Tcanvas. The Screen Variable CB program automatically generates a Screen variable when running, and its data type is Tscreen. To its name, it is packaged in "screen" information and features. We just want to know how much the resolution of the screen is? My computer is (1024 * 768), other computers may be, or 800 * 600, the most misadah is 640 * 480. (Note 1) After getting the screen length (1st, 2 line), we have not used Screen. Screen is automatically generated by CB, a global variable, and its release does not return us.
Screencanvas Variable Tcanvas class, which packages most of the data and features of Windows painting operations. So although its name is "canvas", it is actually "brush (PEN), brush," and so on. In CB, the window comes with a Canvas variable, but unfortunately we are now painting anywhere on the screen. (The first line will pass through the entire desktop from the upper left corner of the screen until the time zone of the lower right corner). This is a very overbearing behavior. CB is of course not preparing such a "canvas" for us. So we need to generate a Canvas variable, I name it as: Screencanvas. This is the 4th line: generate a canvas variable. Although named "Screencanvas". But in fact, the newly generated canvas is "empty picture". Because the program still doesn't know where you want to paint. We want to draw a whole screen (in fact, if you have other programs that are displayed on the screen, you will draw the interface of that program). This needs to be applied to Windows. Please give us "Canvas" of the entire computer screen. Windows is written in C and compliance, both of which are not object-oriented languages. Most of the data and features of WindWos have also been not doing object-oriented packages (later COM objects start with object-oriented features, this is later). In Windows, the type of canvas is called DC. Third line: HDC HDC = :: getdc (0); obtained the screen DC. The parameter 0 is specifying the entire screen of the entire screen. The fifth line: screencanvas-> handle = HDC; through the SCREENCANVAS's Handle property, the entire screen is obtained. (These explanations, you may think that there are still many places that have not been said, but it doesn't matter.) Other, just the process of drawing. Detailed comments in the code. The last 12, 13, 14 three lines are used to returns, release the screen to the screen. This is our first example. Play a fork on the screen. Next chapter we are still going to draw. However, we will be a little bit, only in the right place, draw a suitable content at a suitable time. Guess, what should we draw? It is a content that is very wide and very antique in the programming industry. When I learned "Valley C ", we have done it! - In this case, a piece down is disappointed. Note 1: You can view your computer screen resolution: Right click on Windows desktop, select Properties in the menu that appears, and then selected to the Settings page. The resolution should be found. If not, you can find a "advanced" button. After clicking, look up in each page appearing. Chapter 2, GUI's World (2) Where is the painting?
Previous chapter We speak, in the world of Windows, everything we see is "painting". Also, we boldly painted a red cross on the desktop of Windows. Draw a red fork seems to be very cool, but that program is more like a prank. Just use to prove that we can draw. This chapter, we will learn how to "correctly" painting.
Each "positive" Windows application is often similar, they only draw things in the right time, suitable position. Let's take a look at where the right location is.
2.1 Pictures on your own window
We have said that in the world of Windows, there are countless windows (please review the first chapter). Now let us also create a window - through CB, this is a more prone to things. 2.1.1 Preparation: Create a window
At the same time, studying "Vernacular C " is noticed, we often create "console engine" in "Vernacular C ", which is the "black" window. But in "Vernacular Windows Programming", we are more in creating a normal Windows application engineering with the following steps. Remind you that you will come to a console project, otherwise you will never find the "window".
Run C Builder 6, Menu: File | New | Appication. CB6 is a new blank Windows program engineering. And a form (FORM) is automatically generated. We know that this form is called window (Window) after the program runs. (If you are not familiar with these and some CB related operations, please review the Chapter 2 of "Vernacular C ").
(For CB5, in the menu file, you can go directly to the new application.)
This project is very important, save the project right away! Press Ctrl Shift S. It is recommended to establish a special folder on the disk to save this project. For example, establish: BHWIN / LS2 / PRJ1 / such a folder. As for the CPP file name and engineering name, I just take the default Unit1.cpp and Project1.bpr.
2.1.2 Observe the spider silk mart of a window!
2.1.2.1 The first problem
That's right, this section, we will observe a window like a probe and put forward a problem. To tear a cloth, it is hard to tear the first mouth, one of the following problems is our first mouth of the Windows veil. I hope you can have a good eye.
After saving, what else should we still write, press F9, compile, and run. On my computer, it shows a window. That is the form of Form1 when designing. In order not to occupy too large layout, I pulled the window very small.
(Figure 1: A "bare" window)
This is a bare window ... Is this really a "bare" window? Take a closer look at this window, what can you find? There is a classmate to be deep, and he said that this window is implied with a 3-dimensional vertical figure, and he suggested that you should use the "bucket eye" way to observe ......... Copy! It's so exaggerated. There is such a student, I think everyone should not call my teacher, or call me "master".
In fact, this window is not empty, it has a title bar, the title is: Form1, in the right, there are three small buttons, indicating "minimize", "maximize", "closed" ... listen ... Here, don't be prepared to get out of school! Although these you have long known, we have come out:
Have you ever thought about, the title bar, and the window border, etc., they also draw! However, who did they draw?
The first question: the default graphic element is what is it for us?
2.1.2.2 Second question
Exit Form1, let's put a Button on this form.
First, in the "Standard" page of the CB (that is, first page), find the button control (TButton): (TBUTTON control on the Standard)
There is a "OK" button in the mouse selection, and then place a button on the current form, try to place it in the middle of the form.
(Place a button on the form)
Double-click Button1, appear in the code editing window, enter the following code (black body part):
Void __fastcall tform1 :: button1click (Tobject * Sender)
{
// Set the brush (PEN) of the current client area
Canvas-> Pen-> Color = CLRED; / / The color of the brush is red (Red)
Canvas-> Pen-> width = 10; // Brush's thickness
// Start the fork, need to draw two strokes,
// This is the first: left to the right
Canvas-> MoveTo (0, 0); // Move the brush to (Move to) coordinate 0, 0, ie the origin of the customer area
Canvas-> Lineto (ClientWidth, ClientHeight); // draws a line from the current location to the lower right corner of the client area.
// Second: Top to top:
Canvas-> Moveto (ClientWidth, 0);
Canvas-> Lineto (0, ClientHeight);
}
/ / -------------------------------------------------------------------------------------------- ---------------------------
Also draw a fork, and the first chapter is compared to the screen, the code here has saved a lot. This is because when we painted on a window you generated, many things are available by the CB. For example: "Canvas", there is also the current customer area as long as the CLIENTWIDTH, ClientHeight. (Client is the meaning of the customer). Moveto is "moving to ...", lineto is "drawing line to ..." These two functions in the previous chapter we have used it.
(The student will ask: How do you know the variable canvas, clientwidth, clientheight; how do you know the function Moveto, Lineto? Well, these stuffs will soon know their source, but now it is not explaining these. Vealand C Did the course not to the structure? Soon after learning "class" knowledge, only on the basis of learning "class", we can explain this.)
For the shortcomings, we save the project, press F9, compile, and execute. Then press Button1, the result is as follows:
(Figure 2: Doing fork on the customer area)
After completing Button1, don't move anything, but I guess, you are likely to have been moving, it doesn't matter, then pressing button1, guarantees the figure you see and the picture above.
Then we still come to carefully observe this window! What did you see? The red fork "passed" button, but there is no "painted" button. Why is that?
Furthermore, we are from the coordinates of the window (0, 0), do you pay attention? This coordinate original, is on the upper left corner of the window, not the top left corner of the Plute Carl coordinate system. In addition, this drawing area is not within the title column, but next to the title bar. This explains that we cannot draw on the title by default. Second question: How do Windows decide where to paint when painting?
2.1.2.3 Third Issues
Continue our Holmes Tour!
Press once again to ensure that the red cross is intact. Then, I will drag a different window (such as what you chat with the QQ window), carefully "wipe" the upper right corner of the belt window ...
(I dragged Winamp's window, "Wipe" Form1)
After rubbing:
(After rubbing, the red fork is shorter)
We found that another window, actually like a "eraser", wiped off the red cross on the Form1 window.
Be a trial, or first draw a red fork, then carefully use the mouse to pull the window on the edge of the window, you will find that the red cross is not damaged. But if we get the window first, then pull back the original size, it will find that there is another part of the red fork disappeared.
The third question: Why is it "erased" on the window on the window?
2.2 Painting when needed
I have not prepared to answer all three questions. These problems will no longer be a problem when you have finished learning.
If the program is still running, close it, return to CB.
On the Form1 form, select the button1, then delete it (right, we don't want it).
The mouse click Form1 to ensure that the Form1 itself is selected, then in the control properties window, select the Event page; finally find the onpaint line, as shown:
(Find onPaint Event)
Double-click the mouse or press the Ctrl Enter key in the edit box on the right side of OnPaint. Enter the code editing of the onpaint event response function.
/ / -------------------------------------------------------------------------------------------- --------------------------- void __fastcall tform1 :: formpaint (TOBJECT * Sender) {} // -------- -------------------------------------------------- -----------------
(Form1 onpaint event response function)
(Be careful, this time, don't - is right, don't - save the disk, otherwise, CB will automatically remove it because this event response function is empty, and automatically deletes it.)
Then, we copy the code in the onclick function of the front button, copy to the FormPaint function:
/ / -------------------------------------------------------------------------------------------- --------------------------- void __fastcall tform1 :: formpaint (TOBJECT * Sender) {// Set the brush (PEN) of the current client area Canvas-> Pen-> Color = CLRED; / / The color of the brush is red (red) canvas-> pen-> width = 10; // The thickness of the brush is started, you need to draw two strokes, // It is the first: left to the lower right, canvas-> Moveto (0, 0); // Move the brush to (Move to) coordinate 0, 0, ie the origin of the customer area canvas-> Lineto (ClientWidth, ClientHheight); / / Draw a line from the current location to the lower right corner of the client area. // Second: Right to the left: canvas-> moveto (ClientWidth, 0); Canvas-> Lineto (0, ClientHeight);} // --------------- -------------------------------------------------- -------- (Code Copy from the front button1onclick)
This is then stored.
Make sure you copy the code? If you are copying it on the web, sometimes it will take a space of the Chinese characters, which will not be compiled. No matter how, press the F9 button and run it.
(Another red cross)
Another red cross, but this time, you will use another window to remove, you will find that this redfa is removed.
However, when you adjust the size of the window ... What is found?咦 咦 咦 咦 套::
(Pull the window and pull the window, the red cross is chaotic)
At this point, you should want to recover the red cross, the most direct method is to minimize the window and restore it. Try, and find other ways.
Perhaps there will be a lot of questions, but about "Red Flies", our course is over, what to do, is an extension.
2.3 Hello Windows
Canvas can be used to draw, but also to write. Strictly speaking, everything in Windows is painted in the world, what is the writing? Of course, Windows will not send nerves to let me "draw". In Windows installation directory, there is a Fonts directory, which puts a lot of fonts. The so-called font is to build how to draw a word in advance. With fonts, we can write it very easily on the window.
Remove the code in the previous FormPaint function, change it to the following sentences:
/ / -------------------------------------------------------------------------------------------- --------------------------- void __fastcall tform1 :: formpaint (TOBJECT * Sender) {canvas-> font-> color = CLGreen; / / Canvas font color = green canvas-> font-> size = 24; // canvas the size of the font = 24 (you are now looking at the course, the font size is 9) canvas-> textout (10, 10, "you Good, Windows World! ");} // --------------------------------------- ------------------------------------ (Change the code in FormPaint, let us ask the Windows World Great.)
After f9, the results are shown in the figure:
(Oh, windows, old friends.)
(Maybe, some people have no feelings about Windows? If you like, you can change this sentence to "Anhong, I miss you!", I know you do it.)
This class is here. Remember, more brilliant, more practical Windows programming world, waiting for us later.
Chapter III Message World (1) What is Message
3.1 Send a message to the "Draw" program
3.2 Handling Custom Messages in VCL
3.2.1 Custom Messages
3.2.2 Prepare two windows
3.2.3 Message Send
3.2.4 Processing of Message Receiver
3.2.5 Let Form2 and Form1 display together
3.2.6 operation
3.3 small knot
What is a message? It's really unable to explain. If you ask what is "short message", it is a little answer: that is, you can press eight 摁 on the mobile phone, and finally press the "Send" button, can cause China Mobile or Unicom to deduct you 1 hair or 1.5 is inequal. thing. Or, when you take the train from Beijing to Fujian, all the people received by the mobile phone all the way to your pass, the seven seven eight eight pay:
"Hebei Mobile welcomes you!", "Welcome to Jiangxi Province, Jiangxi Mobile is always serving you!" What would I think? It is estimated to be a sentence: "Hey, you finally arrived!".
Of course, these are spam. Delete is right. However, if you receive additional information? I think of a joke. It is said that a guy is idle when the National Day is long, and the sudden wants to greet your own boss, so I sent a message:
"Boss, happy holidays!"
Soon, the boss returns a text message:
"Thank you, I wish you happiness. Yes, today's company is no longer duty, can you still stare at it?"
It is now possible to mention the term "message driver". Actually, is it simple? The reason why the guy rushed to the streets in the holiday, rushing to the company, is "driven by the news from the boss." Any standard Windows program is "driven" by a variety of messages, while also issuing a wide variety of messages to drive other programs, or drive yourself.
The following figure illustrates the standard Windows program's top level logic - that is, a message receiving a loop of the processing.
(Any Windows program, the top layer is a message loop)
Tell: Some programmers who have already written many programs may question "any Windows program is a message loop": "I wrote a lot of programs, but what news didn't find it?". In fact, this is because when we use VB, PB, Java, Delphi or we write a Windows program in use, the process of usual messages is encapsulated by the code provided behind these tools, and the message processing is mostly A form called "events" is displayed. But this is not equal to we don't need to understand Windows's more essential content. Otherwise, our topics will not be called "see". Theoretical Dongdong is always not intuitive. Come an example, I believe everyone will feel a bit.
3.1 Send a message to the "Draw" program
Please do it one by two steps:
Step 1: The mouse click the "Start" button on the taskbar, "all programs" or "program" -> "attachment" -> "Draw". Will see this Windows old friend. With Windows, you have this program.
(Drawing program)
Make sure: The title text of the "Draw" program you have seen must be as "not named - Draw" shown above. If not, please click on the main menu "File" and select "New".
Step 2: Open C Builder. Create a new Windows application engineering.
2.1 In TFORM1 created by default, put a TButton. (If you won't, look at the previous chapter).
2.2 Double-click Button1 and write the following code in the editing window (bold portion):
Void __fastcall tform1 :: button1click (TOBJECT * Sender) {/ * free version does not provide * /}
(Button1 Onclick event code)
Explanation:
a) NULL is a macro, namely: #define null (void * 0). You can understand it is: 0, or only an empty address. (For the address, see "Vealand C " normally.
b) hwnd is also a type definition alias, namely: typedef void * hwnd. That is, it is a non-type pointer. You can understand that it is just a number: used to numbered each window in each program. We are also used to call this number "handle".
Auxiliary: This chapter is a method of viewing how these macros or aliaword original definitions.
b) FindWindow is the API function provided by Windows (see "Valley C " function sections). This function requires two parameters: "Class name" and "Title" to find the window. "Class name" We have no explanation, here we don't press "Class name", so I gave a null. The title is "unnamed -graph". Please pay attention to 2 spaces in it. If it is actually a non-Chinese version of Windows. That had to look at the title. FindWindows means "Find Window". As the name suggests, it will find the specified window. Let's let it find the number of the master window (handle).
Assistant: This chapter will provide how to find the method of the API function, while teaching the students to configure a more mindful C Builder integrated environment.
c) Does FindWindows find the main window of the "Draw" program we want? We use this sentence to determine:
IF (hwnd! = null)
That is, if the number found is not a 0, it is found. d) What do you find later? This is the key to this program. We will send a message to the found window. SendMessage is also an API function. As the same as the name suggests: its function is "Send Message". It requires 4 parameters:
The first parameter indicates "Who Send Message", the target window, here is the main window we find, the drawing program.
The second to four parameters are used to indicate "what message". WM_Close is also a macro. In fact, it is affirmed integer, maybe 101, or may be 777? What is the specific, if you use VB or PB numbers, I am afraid I have to pay some strength to check. And we don't have to use C , because Windows itself is written with C, we can use the macro provided by Windows. But what does this macro mean? In Windows, "Message" consists of three integers: The first integer is the number of messages, and the rest is the parameters of the message. "Wm_close" means a message that turns off / close. This news doesn't need any parameters, so the rest of the two parameters, we all fill in 0, namely:
SendMessage (HWND, WM_CLOSE, 0) // Represents: To the HWND window, send a WM_CLOSE message, with a parameter of 0.
e) Think about it, is our program now have some "China Mobile"? People's drawing program stays well on the screen, don't move, don't rest, we will send it a message in desperate. Moreover, China Mobile is good as a "welcome" message, and we send it, you will understand that this is a "glow" message.
A program that receives another program forced the "Roll" message. What is the result? There are two types: the first is "inversely" type, that is, it is really disappearing. The other is "resolutely ignore" type.
The drawing program, the old employees of this Windows are typical inversely. Without further ado. Save the project, code. Press F9! Make sure your draw is still running on the desktop. Then press the Button1 of our program. You will find that the drawing program is automatically exited.
Try: Double-click "My Computer" on the computer desktop and open the "My Computer" window. Then modify the window titled "My Computer" in the front code. Rebate, run, click on Button1 ... what is the result? Once, I remember Windows95? This is ok, the "My Computer" window of Windows. This method can also be closed. Now, I only heard "When" ... "What did this" when "said" My Computer "tried to get" short messages "to us?)
Auxiliary: The auxiliary teaching materials will provide "password viewer" implemented in the same principle. Like many netizens, I have applied for a lot of free email online. Then install a foxmail on the machine. Sign in to these mailboxes need a password, but after foxmail, set it in one month, I forgot what these passwords are. The Foxmail password is displayed in "*******". How to do? Still sending a "I want to see your text" to foxmail, then watching foxmail is "reverse" or "resolutely ignorant".
3.2 Handling Custom Messages in VCL
If you don't negotiate, you will send another program (such as "drawing"), how to say that it is not polite.
Let's send a message to your own window. Borland C Builder provides a set of procedures for the shape of various windows of the gate Windows, called VCL (visual component libraries). Of course, it also includes a method of processing various Windows common messages. Therefore, in most cases, we don't have to worry about how to handle messages that all applications have to be processed. In fact, this processing process is quite boring because there are thousands of articles. However, Windows also allows us to customize messages and then send and process these messages in the program.
With more interesting, in order to better understand a "message" from the complete process of born to death, there is this section.
3.2.1 Custom Messages
As mentioned earlier, the message requires three unsigned integers: the number of messages, two parameters of the message.
In order not to repeat with Windows predefined messages, Windows specifies that our custom message must start from a base. This base is also defined as a macro: WM_USER.
As for the two parameters of the message, it is entirely defined by us. In fact, this is just a "agreement", that is, you must have the meaning of these two parameters between the "sender" and "recipients" of the message. Imagine, if you send you a wife, "7521", your original meaning is "Wife, I love you", more sweet ... But if you don't have prior agreement, who dares to ensure that your wife will not understand as "bullying my child " So it is important to ensure that this agreement is important. Even if we are like this, the "definition", "sender", "sender", "Receiver", is also careful. How to ensure that it is wrong? Of course, it is also defined by macro. It is a good way to define integers as a literal macro.
Since the macro of the Windows Many messages is started with "WM_", in order to expire, the macro of the user-defined message is through "cm_".
Let's talk about what we have to do? Suppose we have to send a message, after the window is connected to this message, you can move the specified distance in "upper, lower, left, right" in a certain direction.
/ / Customize the message number, based on WM_USER, we will start from adding 1 year.
#define cm_movewindow (WM_USER 1)
Next, we have a convention: the first parameter, which is used to indicate which direction movement, in order not to miss, we define an enumeration type representation:
ENUM TMOVEDIR {MDLEFT, MDBOTTOM, MDRIGHT, MDUP}; // Left, Under, Right,
The second parameter is used to indicate the distance to move.
That is to say, if a window receives this information:
CM_MOVEWINDOW, MDLEFT, 2
So, this window should take the initiative to move to the left, move 2 pixels.
After the appointment, you can start writing the program. Let us build a new Windows application project in CB (the original engineering remember saves).
3.2.2 Prepare two windows
First, the new project will generate a primary form by default, put a tag control on the form: TLABEL. The name is default Label1.
Second, select the main menu "File" -> "new" -> "form", let us build a form, the newly created form is default named FORM2, we use it to send a message. And the original form (main window) is used to receive messages.
Third, in order to ensure that FORM2 can be created automatically, after completing the second step, click on the main menu "Project" -> "Options", find "Forms", make sure that Form1 and Form2 appear on the left list. If not, move to the left through the "<" button on the interface. (Make sure that both forms are on the left side)
Confirm that the dialog exits the third step.
Fourth, change, the position, size of Form1, Form2, and place four buttons on Form2, pay attention to the position and order of the placed on the graph. Finally, as shown below.
(Left is Form1, the lower right is Form2)
3.2.3 Message Send
5. The mouse click on the title of FORM2. Press F12 to open unit2.cpp; press Ctrl F6, or click on the Edit box, open the header file of Unit2: "Unit2.h". Enter the following bold code, that is, our previous agreement.
... #include
(Add code in unit2.h file)
6. Switch back to Unit2.cpp, the upper part of the code is added to the following bold line, that is, unit1.h. Because we need Unit2.cpp to use Form1 in Unit2.cpp, and Form1 is defined in unit1.h.
/ / -------------------------------------------------------------------------------------------- --------------------------- #include
(In Unit2.cpp, include unit1.h)
Seven, on Form2, double-click Button1, enter the following bold part of the code in the code editing window.
Void __fastcall tform2 :: button1click (TOBJECT * sender) {// Send "Move" message, requires up to move up 10 pixel locations: / * Free version does not provide * /}
(Button1 onclick code: message to move 10 pixels))
8. Similar to the seventh step, click Button2, Button3, Button4, complete the input of the following bold part of the code:
Void __fastcall tform2 :: Button2click (TOBJECT * Sender) {// Send "To the left shift" message, request to move 10 pixel locations to the left: / * Free version does not provide * /} // ------- -------------------------------------------------- --------------------_fastcall TFORM2 :: Button3Click (TOBJECT * Sender) {// Send "To Right Transfer" message, require 10 pixel locations to the right: / * Free version is not available * /} // --------------------------------------- ------------------------------------ Void __fastcall tform2 :: button4click (Tobject * sender) {// Send "Down" message, ask for 10 pixel locations down: / * Free version is not available * /} // --------------------- -------------------------------------------------- ----- (Complete the remaining three directions)
Now we have completed the code that sent the message section. The processing is received below.
From the above code, we see that the message is sent to "form1-> Handle". The form created by default, and Handle is the window handle of the form by default. Therefore, the recipient of the message is Form1.
Switch to Unit1.cpp, then press CTRL F6 to switch to unit1.h.
Auxiliary: Basic Usage of C Builder Integrated Environment.
3.2.4 Processing of Message Receiver
Nine, in Unit1.h. Plus the reference to Unit2.h:
#include
Ten, in the VCL, there is a special method to complete the message response. Please click in Unit1.h, click the right mouse, in the pop-up menu, select "View Explorer", or press Ctrl Shift E directly. A "class expert" window appears:
(Class expert window, when the window appears, it may be "nested" in the code window)
XI, as shown above, select TFORM1. Then click the right mouse button. In the pop-up menu, select "New Method ...". We will create a new member function for TFORM1.
(New Method: Create a member method for the specified class)
12. In the dialog box, the following red circle is indicated:
/ * Free version does not provide * /
(Add method: Add method)
Thirteen, click OK to exit, the CB will add a function in Unit1.cpp. Please add the following streaks of code.
Void TForm1 :: CmmoveWindow (TMESSAGE & MSG) {// Todo: add your source code Here if (msg.msg! = cm_movewindow) return; // lparam is the second parameter of the message, the distance to move: int LEN = MSG .Lparam; // wparam is the first parameter of the message, agreed to indicate the direction of the mobile: switch (msg.wparam) {case mdleft: left = left - len; label1-> caption = "left shift"; Break Case MDRight: Left = Left LEN; Label1-> CAPTION = "Shot"; Break; Case MDUP: TOP = Top - Len; Label1-> CAPTION = "Move"; Break; Case MDBOTTOM: TOP = TOP Len; label1-> caption = "Down"; Break;}} (received, code processing)
3.2.5 Let Form2 and Form1 display together
14. Compile and run the program now, you will find that I only see Form1, but I can't find Form2. This is because only the default generated main window, that is, Form1, will be automatically displayed. Therefore, we want to display FORM2 when Form1 is displayed. Please click on Form1 with the mouse. Press F11 to find the control properties window and switch to the Event page:
(Find the onshow event of Form1)
As shown in the figure, find Onshow, then double-click on the right blank with the mouse.
Fifteen, in the code editing window, join the thickened line of code:
Void __fastcall tform1 :: formst * sender) {/ * free version is not available * /} // --------------------------- ------------------------------------------------
3.2.6 operation
16. Isn't there a code yet now? This is very dangerous. Save (Ctrl Shift S). Then press F9 to compile and run. Press FORM2 four buttons, see if the shape of Form1 is correct. Below is a screenshot running on my machine:
(Finally run screenshot)
I can't see a long process, we have completed the three major steps of "definition, send, and process" messages. In fact, to complete the same feature, it is entirely possible without processing (auxiliary: non-custom message "version of this example). But through message processing, we can make the program more flexible in design, and the focus of this chapter is to establish the concept of "message processing".
In this example, the four buttons in FORM2 will issue CM_MOVEWINDOW this message to FORM1. Remember: CM_MOVEWINDOW is just an integer. The program does not automatically move the Form1 up and down by this macro with the text of "Move Window"! To complete the relevant processing, you need to work on our code. The message has two parameters. These two parameters are also integers, and their specific integration, how to use, the same dependent on actual code. 3.3 small knot
This chapter has only two sections.
In the first quarter, we tried to an external program: "Draw", send a Windows predetermined message: WM_Close. After receiving the message, the "Draw" program will make predefined actions: exit. But for other programs, it may be judged and found that the message comes from the outside, not processing.
In the second section, we send custom messages between two different windows in the same program. Thus, we learned that the original Windows message consists of three parts: message number, and two message parameters.
This is the point of this chapter. If you don't know if there is "news" in the world of Windows, now you should have something to know. However, if you just look at the course, just a Copy code, now you are looking back and then watching it again.
The next chapter will see.