Windows programming initial

xiaoxiao2021-03-06  19

Windows programming is currently a household name, its history is the most brilliant page in Microsoft History. People now have basically used Windows operating systems, so we need to program Windows from the DOS environment programming. This article Will introduce you to Windows technical features, friendly interfaces and their internal engines. In addition to the introduction to the basic concepts of the Windows system, the Windows program written with the C language and Windows SDK will make readers to programming the Windows. Learn, although we have not entered the MFC programming that uses VC, it can lay the foundation for the classmates who are going to learn Windows programming. This article is divided into several parts: one. Windws type operating system Technical Features II. Windows window and control three .Windows internal engine four. Write a Windows program, then let's go into Windows programming vast world! The technical features of the .windws class operating system:

Standard user interface: In all Windows technical features, the standard graphical interface is the most familiar, most popular. All Windows programs have similar appearances and the same standard control, and users no longer need long-term Learning can use the newly developed software. With the evolution of Windows, the user interface is constantly rich, more and more convenient for users. Multi-task: Support multitasking is another success of Windows, users can run multiple applications at the same time under the operating system, can move the window at any time, change their size, switch between windows, can also exchange between windows Information. Before the multitasking operating system appears, the application monitors all resources of the computer, including input and output devices, memory, and display devices, even CPU itself, but under Windows, these valuable resources must share. Excellent memory management: Users who have used DOS must remember the valuable 640KB regular memory. In the DOS environment, if you want to prepare a more than 640KB application, programmers should dig empty mind to optimize memory, and even write memory management programs. But in my own Under Windows, memory is an important shared resource. For this important resource, Windows must be managed by yourself. But everyone can rest assured that Windows's memory management strategy is savvy, this is to be attributed to Microsoft's excellent Windows software engineers. Windows passed Movement code and data in memory, you can collect a broken block, which make up a large free memory block. In addition, there are many techniques to share memory, such as dynamic link libraries. For users, memory is flat (Flat Memory, therefore, Users don't have to consider the problems of segment when programming under DOS, just propose memory allocation requirements, other handed over the operating system, Windows will give you a reply. Detective independence: Another main feature provided by Windows is the independence of the application for hardware devices. With the development of electronic technology, computer technology, hardware equipment has become faster and faster, the application must face a variety of hardware devices. The drivers of all devices that are expected to be used in non-Windows applications, the most The main thing is to display devices and printing equipment, which greatly affects software development efficiency. Windows liberates program designers in this area, under Windows, the display, printer, keyboard mouse driver only one can be installed Support for each application. Software developers can use the general interface provided by Windows, which eliminates a large number of repetitive labor in programming.

The above is the main technical characteristics of Windows, and the Windows has many other technologies, such as network functions, multimedia technology, etc. It can be said that Windows fully utilizes the resources of the PC, and also gives PC powerful vitality. Two .Windows window and Controls: Windows has a friendly and gorgeous interface. The window is the basic interface unit of the application in Windows itself and the application in the Windows environment. The reason is that because the Windows control is also a window, it is just a special window. From the perspective of users Look, the Windows window is a rectangular area displayed on the screen, which is independent of the application, which is an intuitive interface that generates the window and the program user. From the perspective of the application, the window is controlled by it. Part of the rectangular screen area. Application generates and controls everything related to the window, including the size of the window, style, location, and window displayed in the style. After the user starts an application, the program will create a window and there Waiting for the user's request. Whenever the user selects the option in the window, the program responds to this. Whether it is Windows95, WindowsNT4.0, or the Windows98 User Program Interface API is Win32API, so they are mostly the same. The 32-bit operating system represented by Windows98 also supports many new public controls, which make the application more flexible, and make the application more beautiful. There are many common controls in Windows, these controls we have started in VB zero. Or introduced in other articles, here is not described in detail. This is to explain that this article is intended to lead everyone to enter the Windows programming field, and the programmed language is C or C . The following example is also written using VC6.0. Three. Windows internal engine: Here I want to say more about Windows's internal engine, because this is very beneficial to understand the basic idea of ​​Windows programming. 1. Event drive model and message loop: classmates who have used TC should know The procedures developed under DOS are mainly used in order of process driver design methods. Please pay attention to the process driver this concept, in this design idea guide, the next program will have a clear start, obvious implementation process and a significant end During the execution of the program, the program can directly control the order of program events or processes. However, in the Windows programming method, the above-mentioned process driver is to be completely broken .Windows programming method and DOS program design The difference is that the Windows program is an event-driven. The event-driven program is controlled by the incident. This design idea is a non-sequential manipulation event, thereby avoiding the order of the process. Then come first Learn about what is an event The meaning of the event is wide, the most common is the mouse event, including the mouse movement, click on the mouse button, the mouse is located in the window. After the application is started, the program is waiting for the event, when an event occurs Perform a corresponding process, perform specific functions. Events can also be defined by the user, for example, a certain program process can also be used as an event. Event driver design is expanded from the generation and processing of messages. One message is Information about the event that happens. For example, a key or mouse button is pressed, a message, while when it releases, another message has occurred again. As a Windows programmer, your Windows application does The main work is to handle various messages. The execution order of the application is also unpredictable, and the generation of messages is not only derived from the keyboard mouse. The message can be generated by the application itself, or can be generated by other programs running. You can be generated by the user or Windows. Whenever the event occurs, the Windows is recorded and the corresponding message is assigned to the relevant application. If the beginner does not experience the Windows message, you can experience the presence of the message. In VC The SPY tool is selected in the Tool menu of 6.0, which can monitor the generation of messages. It also found the tool in the Microsoft Visualstudio6.0 Tools program group. Click the Spy icon, open the window as shown: Figure 1 Spy work window Open The SPY menu of the main menu, select the Message command (Ctrl M), start the Message Options dialog, there is an icon for a window on the Windows page, put "Bull"

Drag to the window you want to make a message monitoring, such as you can drag it on the desktop, this is what you can observe the message received by the desktop. Select the Message page, this is a message filter user can choose the message of interest. Monitoring, by default, all messages are selected, click OK to exit. SPY Workspace Now open a new window to display the content of the message. This is where you can see the record window on your desktop. There is a message record in the middle. The name of the message is started with "WM_", for example, WM_SETCURSOR is a mouse cursor, WM_Mousemove is a mouse mobile message. As shown: Figure 2 Observe Windows Message Windows for the application The message provides a reserved area called Message Queue. Each of the operating system has its own message queue in the executed program (including applications and system itself). By operating system and other applications or All messages sent to the application are stored in the queue, each message is waiting to be called in the team. The Windows application calls the Windows message at a specific loop, which is the Message Loop. Message loop It is a simple While () loop, he will run, know that the message to be terminated will close the application, stop the loop. The following figure shows the process and message loop and processing mechanism of the Windows application. Figure 3 Windows application Process, message loop and processing mechanism 2. Multi-task's insider-process and thread multitasking operating system is another important feature of Windows. When users open multiple windows in Windows or while listening to MP3 When Windows itself is busy performing the switching of each application, working in time. Although it looks on the surface, it seems that multiple applications are carried out at the same time, but the single CPU machine, no matter at any time, where Only one program can truly occupy the processor. Multi-task mechanism in Windows uses the concept of process and threads. Process is a run routine for the application. Another application must have multiple routines, such as drawing, writing board, etc. Applications can open multiple copies, and some applications can only have one routine running, such as the SPY tool just used. Each process consists of several code and data blocks. Theoretical, 32-bit Windows applications The process has 4GB virtual address space, of course, there is still no big program. Each process also has its own resources, and threads. Thread is a execution unit in the process. Each thread in the process corresponds to one Group CPU instructions, a set of CPU registers, and a stack. There is at least one "main thread" in a process, of course Take multiple threads. The process is actually performed by the thread. The best Windows NT in the Windows family is designed to run on a computer with multiple CPUs, and there are more processes and threads to actually run. And is all modified to all valid CPUs, which is of course ideal. The current PC is mostly a single CPU machine, then the clause must queue the "machine", and it is valid according to the order. Execution time. This short period is called time film. When a thread is used, it will be forced to transfer to the "sleep" state, wait until the next round of valid time film arrives, it will be re-"awake", Continue to execute. Of course, before "Sleep" and "Wake-up" to save the running environment and restore the running running environment. Windows In addition to the queuing mechanism, the process and thread has its own priority in addition to the queuing mechanism. The priority process and thread will get more time slice. In the application, programmers can develop a strong task handling and non-test functional task processing by priority development. We now You can experience the existence of the process and thread. We can still use the Spy tool, you will find Spy is really useful. Open the Spy menu, select the process command (Ctrl

P). There is a window that has a running process in the system in the work area. The hexadecimal number after each process is the logo in the system, and the name is the name of the process. Tree graphs list the thread of the process. Some threads are open, and the windows belonging to the thread are listed. Select threads or processes Double-click the mouse to list the details of the process and threads. See priority ( Priority base). Figure 4: Details of the processes and threads listed in SPY 3. Application shared resource --- Dynamic Link Library Technology Dynamic Link Library Technology as an important technology of Windows, its technical ideas are not the origin The standard function library of C language in the Windows.DOS environment is very familiar. C language is running on its Runtime library. We write calling statements, the link program will call the function (such as Printf, getchar we are familiar), Copy the program from the arithmetic function library to form an executable file. This method of linking C runtime library is called a static link. This method of static link is largely liberated, so that it does not have to prepare such as read and write characters. Or format the utility of the output, these codes of the run library are copied into the user's code when the link is linked. In addition, programmers can easily build their own libraries, including their usual features and standard libraries There is no function. This kind of public function becomes the idea of ​​tools, eliminating the phenomenon of repeating design, but there are many problems in the Windows multi-tasking environment. Multiple programs share memory in the Windows environment, each program Save a public function copy, which obviously leads to a waste of memory. For example, each program uses to getChar () function, the static link library will copy a getchar () function copy to each application, and multiple multiple GetChar () Copy This is clearly very wasting memory space. Therefore, the concept of dynamic links. Windows libraries are dynamic links. The linker does not copy the library function to the program's executable, but by the executable of the program The library function is called during the execution process. This method saves memory, no matter how much parallel program, when you use a function, the function has only one copy in memory. In addition, when the function is modified, you do not have to resin the call to call the function. Of the executable. In Windows, most features are implemented with dynamic link libraries (.dll files). The dynamic link library is the core and essence of Windows, because several major modules of Windows are all dynamic link libraries .Windows The application interface (API) provided to the user also uses the dynamic link library (hereinafter a section will say). The essence of the dynamic link library is an executable module. It can include all functions of the Windows application, and Resources and other code. But dynamic links The library itself will not run itself, it will reside in memory and other applications call it. In VC 6.0 we can write your own dynamic link library. We will see a lot in the System folder under the Windows directory. Link Library (* .dll). IV. Write a Windows Program: Below I want to use the API and SDK to write a simple Windows program in which Windows is reflected. I want to introduce you to everyone before writing this routine. Application Interface API and Development Toolkit SDK concept. API This word refers to an application design interface. It is a function in the program. We can use it to create other programs. Don't know in the process of calling Internal implementation, as long as it knows the prototype and return value .Windows API is the most famous API today, which is implemented through the DLL, any language that supports Windows API can write a Windows application .Windows API itself is Windows programming Based, itself includes the basic concept of Windows. However, due to the complexity of the Windows itself, the intrinsic mechanism of many API functions is also very complicated. The relationship between API functions is also very complicated, and some API is equivalent to the compilation of Windows applications. Language. Many programming languages ​​not only support Windows API, but also encapsulate API, such as MfcDelphi, C Build, etc., through its own function class library, which is ultimately transformed into API. Three dynamic link libraries in the Windows core constitute the main body of Win32 API:

User32.dll: Responsible for window management, including messages, menus, cursors, communication, timers, and other control display windows. GDI32.DLL: Graphics device interface, he manages user interface generation and graphics, including device description table , Font, bitmap, etc. KERNEL32.DLL: Windows core, he manages low-level functions such as memory scheduling, process schedule. Early Windows SDK.sdk is the software development kit, Windows SDK contains the following: Describe Windows functions, message , Structural, macro and resources, various tools, including dialog editor, resource editor. A set of Windows libraries and header files. Windows program samples written in C language. Windows SDK has an important development of the early development of Windows applications Tools. But he still seems to be a comparative work that is still far from the development of the Windows application. But the document in the SDK is very valuable. They are the most comprehensive technical information of the public Windows. Microsoft, Borland, Watcom and other companies absorb the main content of SDK to their own compiler products. These new products use the object-oriented technology packaging Windows API. It can be said that the main difference between SDK and these products is the difference between C and C . However, in some cases, use the API to solve the problem more direct, more deeper, just like mixing of the C language assembly language. Well, don't say anything else, start our first Windows program. Understand the API help It is very good to understand the internal operation mechanism of the Windows, so we write a Windows program with API before the beginner contact MFC. We write this program with VC 6.0, first open the VC 6.0 to open the File menu, the new command is established Win32 Application Type Project, Note, select "A Simple Win32 Application." In step 2 when establishing an engineering. The file will be sent to the following: // Demo: Demo to develop Windows Application // Function: When the mouse button is pressed, the pop-up message box notifies the user to press which button of the mouse // ****************** Source code ******* ************* * INCLUDE "stdafx.h" int Pascal Winstance, Hinstance Hprevinstance, LPSTR LPSZCM DPARAM, INT NCMDSHOW; LRESULT CALLBACK WNDPROC (HWND HMAINWND, // Window Handle Uint Message, // Message Identifies WPARAM WPARAM, // Message Additional Information LParam LPARAM); // Message Additional Information // The following definition global variable // instance handle hINSTANCE myhInst; // application name char szAppName [] = "WinAPIDemo"; // program title char szAppTitle [] = "Windows application using the application program interface"; INT PASCAL WinMain (hINSTANCE hInstance, hINSTANCE hPrevInstance, LPSTR lpszCmdParam , Int ncmdshow; {// main window handle (handle is identified in Windows) hWnd hMAINWND; / / Define Windows Message Data Structure MSG Message; // Defines Window WordClass MyWc; if (! Hprevinstance) // Decision There are other applications instances run {// The following is the window assignment mywc.style = cs_hredraw | cs_vredraw; mywc.lpfnwndproc = WndProc;

myWC.cbClsExtra = 0; myWC.cbWndExtra = 0; myWC.hInstance = hInstance; myWC.hIcon = LoadIcon (NULL, IDI_APPLICATION); myWC.hCursor = LoadCursor (NULL, IDC_ARROW); myWC.hbrBackground = HBRUSH (GetStockObject (WHITE_BRUSH) ); myWC.lpszMenuName = NULL; myWC.lpszClassName = szAppName; // Register the window RegisterClass (& myWC);} // create the application window hMainwnd = CreateWindow (szAppName, // window class name szAppTitle, // window title WS_OVERLAPPEDWINDOW, / / Window Style 200, // Initial X Coordinate 200, // Initial Y Coordinate 400, // Initial Width 500, // Initial Height NULL, // Parent Window Handle Null, // Window Menu Handle Hinstance, // Program Current Handle NULL / / Create parameters); showWindow (hmainwnd, sw_showmaximized); // Display window UpdateWindow (HmainWnd); // Refresh Window User Zone While (GetMessage (& Message, Null, 0) // Create a message loop {TranslateMessage & Message); // Translation Keyboard Message DISPATCHMESSAGE (& Message); // Send a message to message processing module} return message.wparam;} / ********************* *********************************************************** Funct ION: WNDPROC (HWND, UINT, WPARAM, LPARAM) window processing PURPOSE: Processes Message processing message ****************************************** **************************************************************** / LRESULT CALLBACK WNDPROC (HWnd Hmainwnd , // window handle Uint message, // message Identification WPARAM WPARAM, // Message Additional Information LParam LPARAM) // Message Additional Information {Char Msglbtn [] = "You just pressed the left button!"; Char msgrbtn [] = "You just pressed the mouse button!" , MB_ok | MB_ICONITION; Break;} Case WM_LButtondown: // The left mouse button is pressed {MessageBeep (MB_ICONIONFORMATION);

MessageBox (Getfocus (), Msglbtn, "Message", MB_ok | MB_ICONInformation; Break;} case wm_destroy: // Close window {PostquitMessage (0); return 0;} default: Break;} // Not included The process of processes Return DefWindowProc (HmainWnd, Message, WParam, LParam) by Windows;} Ok, the program is running, you can see the results shown in the figure: Figure 5 API written Windows program running results Run You may feel some disappointed because you wrote that long code, this is indeed, it is indeed a cumbersome thing that uses API writes, but in many places can reflect the contents of the Windows running mechanism. For routines Analysis: 1. Main function WinMain (): (1) The entry of the Winmain program: This is similar to the main () function in the C program under DOS, and the entry of the Windows program is WinMain (). In Winmain this master block To complete the registration window type, create a window, display window, create a message loop, etc. To note: the Pascal keyword before WinMain (), the program is called the function according to the PASCAL Call rule. (2) Register the window with the RegisterClass function : Any window to display first to register in Windows so that you can manage in Windows. To define window classes before registration. The window class is the structure of the record window information in the program WNDCLASSMYWC is the data structure that defines a window class. MYWC. STYLE / / Definition window type, style mywc.lpfnwndproc // definition window process program name mYwc.hinstance // window The current handle MYWC.HICON / / window with the icon MYWC.HCURSOR / / DEVITED NOWC.HBRBACKGROUND / / Define window background MYWC.LPSZMENUNAME // Window menu name, if any, use mywc.lpszclassname // definition of the resource definition program to define the window class after the window class is defined after the window class is defined. Use registerclass (& MYWC) The statement can establish an instance of the window after registration. The API function createWindow used by the window class includes the name, title, window style, display location, window size. So far, the window to create is ready to be ready, only waiting Displayed. (3) Display the window with the ShowWindow function. (4) Set a message loop mechanism: The message loop is implemented with the While loop. Name: while (GetMessage (& Message, NULL, 0, 0)) // Establish Message Cycle {TranslateMessage (& Message); // Translation Keyboard message DispatchMessage (& Message); // Send message to message processing module} where a getMessage function removes a message from the message queue and put it in the WINDOWS message structure MSG. The meaning of the MSG structure is as follows: typedef struct tagmsg {hwnd hwnd; // window handle, Windows The unique identifier for each window is given to window management. Uint message; // message value, is the identifier of the message, in Windows. The H header file is defined. WPARAM WPARAM; // Message additional parameters, content containing the message. LPARAM LPARAM; // Message additional parameters, content containing messages .WParam, LPARAM is an important basis for processing messages. DWORD TIME; // message Feed into the team. Point Pt; // Message The screen coordinate of the time scale.} MSG;

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

New Post(0)