MFC Application---The Frame Window Object

VC++6.0项目精讲:从Win32到MFC,掌握Windows桌面开发核心 Windows桌面应用程序开发的核心在于理解其底层运行机制,这通常涉及对Windows API的调用、消息循环的处理以及运行时库的依赖。消息循环是Windows程序的心脏,它负责从系统队列中获取并分发用户输入和系统事件,驱动程序运行。动态链接库(DLL)和运行时库(如MSVCRT)的管理则是确保程序可移植性和部署成功的关键技术,它们解决了代码复用和依赖问题,这也是现代应用(如Flutter桌面端)打包时仍需处理VC++库依赖的根本原因。掌握这些原理,对于维护遗留系统或理解现代框架的底层封装都极具价值。本文将 阅读详情
 

The Frame Window Object

MFC's CWnd class and its derivatives provide object-oriented interfaces to the window or windows an application creates. Hello's window class, CMainWindow, is derived from MFC's CFrameWnd class, which is derived from CWnd. CFrameWnd models the behavior of frame windows. For now, you can think of a frame window as a top-level window that serves as an application's primary interface to the outside world. In the greater context of the document/view architecture, frame windows play a larger role as intelligent containers for views, toolbars, status bars, and other user-interface (UI) objects.

An MFC application creates a window by creating a window object and calling its Create or CreateEx function. Hello creates a CMainWindow object in CMyApp::InitInstance. CMainWindow's constructor creates the window you see on the screen:

Create (NULL, _T ("The Hello Application"));

_T is a macro that's used to make string literals character set neutral. It's discussed later in this chapter. Create is a CMainWindow member function that's inherited from CFrameWnd. It's one of approximately 20 member functions that CFrameWnd defines in addition to the functions it inherits from CWnd. CFrameWnd::Create is prototyped as follows:

BOOL Create (LPCTSTR lpszClassName,
    LPCTSTR lpszWindowName,
    DWORD dwStyle = WS_OVERLAPPEDWINDOW,
    const RECT& rect = rectDefault,
    CWnd* pParentWnd = NULL,
    LPCTSTR lpszMenuName = NULL,
    DWORD dwExStyle = 0,
    CCreateContext* pContext = NULL)

Default values are defined for six of the eight parameters Create accepts. Hello does the minimum amount of work required, specifying values for the function's first two parameters and accepting the defaults for the remaining six. The first parameter—lpszClassName—specifies the name of the WNDCLASS that the window is based on. Specifying NULL for this parameter creates a default frame window based on a WNDCLASS registered by the framework. The lpszWindowName parameter specifies the text that will appear in the window's title bar.

The dwStyle parameter specifies the window style. The default is WS_OVERLAPPEDWINDOW. You can change the window style by specifying an alternative style or combination of styles in the call to Create. You'll find a complete list of window styles in the documentation for CFrameWnd::Create. Two of the styles frequently used with frame windows are WS_HSCROLL and WS_VSCROLL, which add horizontal and vertical scroll bars to the bottom and right edges of the window's client area. The statement

Create (NULL, _T ("Hello"), WS_OVERLAPPEDWINDOW ¦ WS_VSCROLL);

creates an overlapped window that contains a vertical scroll bar. As this example illustrates, multiple styles may be combined using the C++ ¦ operator. WS_OVERLAPPEDWINDOW combines the WS_OVERLAPPED, WS_CAPTION, WS_SYSMENU, WS_MINIMIZEBOX, WS_MAXIMIZEBOX, and WS_THICKFRAME styles, so if you'd like to create a window that looks just like a WS_OVERLAPPEDWINDOW window but lacks the maximize button in the title bar, you could call Create this way:

Create (NULL, _T ("Hello"), WS_OVERLAPPED ¦ WS_CAPTION ¦
    WS_SYSMENU ¦ WS_MINIMIZEBOX ¦ WS_THICKFRAME);

An alternative way to specify a window style is to override the virtual PreCreateWindow function that a window inherits from CWnd and modify the style field of the CREATESTRUCT structure passed to PreCreateWindow. This capability is handy to have when the framework creates your application's main window for you, as is frequently the case in document/view applications, but it's not necessary when your code calls Create directly and therefore controls the parameters passed to it. Later in this book, you'll see examples demonstrating when and how PreCreateWindow is used.

Additional window styles known as extended styles can be specified in CFrameWnd::Create's dwExStyle parameter. Window styles are divided into standard and extended styles for a historical reason: Windows 3.1 added support for additional window styles by introducing the ::CreateWindowEx API function. ::CreateWindowEx is similar to ::CreateWindow, but its argument list includes an additional parameter specifying the window's extended style. Windows 3.1 supported just five extended styles. More recent versions of Windows offer a much greater selection that includes the WS_EX_WINDOWEDGE and WS_EX_CLIENTEDGE styles, which give window borders a more pronounced 3D look. MFC automatically adds these two styles to frame windows for you, so you rarely need to specify them yourself.

After the dwStyle parameter comes rect, which is a C++ reference to a CRect object or a C-style RECT structure specifying the window's initial screen position and size. The default is rectDefault, which is a static member of the CFrameWnd class that simply tells Windows to choose the window's default initial position and size. If you want to, you can specify the initial position and size by initializing a CRect object with coordinates describing a rectangle on the screen and passing it to Create. The following statement creates a standard overlapped window whose upper left corner is located 32 pixels to the right of and 64 pixels down from the upper left corner of the screen and whose initial width and height are 320 and 240 pixels, respectively:

Create (NULL, _T ("Hello"), WS_OVERLAPPEDWINDOW,
    CRect (32, 64, 352, 304));

Note that the window's width and height are determined by the difference between the first and third parameters and the second and fourth parameters rather than by the absolute values of the third and fourth parameters. In other words, the CRect object specifies the rectangular region of the screen that the window will occupy. The four parameters passed to CRect's constructor specify, in order, the rectangle's left, top, right, and bottom screen coordinates.

The pParentWnd parameter to Create identifies the window's parent or owner. Don't worry for now about parents and owners. This parameter is always NULL for top-level windows because top-level windows have neither parents nor owners. (Actually, specifying NULL for pParentWnd makes the desktop window—the window that forms the backdrop for the screen—the window's owner. But that's an implementation detail that matters only to Windows.)

Create's lpszMenuName parameter identifies the menu associated with the window. NULL indicates that the window has no menu. We'll begin using menus in Chapter 4.

The final parameter to CFrameWnd::Create, pContext, contains a pointer to a CCreateContext structure that is used by the framework when it initializes frame windows in document/view applications. Outside the document/view architecture, this parameter is meaningless and should be set to NULL.

Create offers a tremendous variety of options to the programmer. The number of choices might seem overwhelming at this early stage, especially if you haven't programmed for Windows before, but experience will teach you how and when to exercise the options available to you. Meanwhile, the class library's use of default function arguments hides much of the complexity when a standard CFrameWnd-type window is all you need. This is one example of the ways in which MFC makes Windows programming just a little bit easier.

Painting the Window

Hello doesn't draw to the screen just whenever it wants to. Instead, it draws in response to WM_PAINT messages from Windows signaling that it's time to update the window.

WM_PAINT messages can be generated for a variety of reasons. A WM_PAINT message might be sent because another window was moved, exposing a part of Hello's window that was previously obscured, or it could be sent because the window was resized. Whatever the stimulus, it is the application's responsibility to paint the client area of its window in response to WM_PAINT messages. Windows draws the nonclient area so that all applications will have a consistent look, but if the application doesn't implement its own drawing routines for the client area, the interior of the window will be blank.

In Hello, WM_PAINT messages are processed by CMainWindow::OnPaint, which is called anytime a WM_PAINT message arrives. OnPaint's job is to draw "Hello, MFC" in the center of the window's client area. It begins by constructing a CPaintDC object named dc:

CPaintDC dc (this);

MFC's CPaintDC class is derived from MFC's more generic CDC class, which encapsulates a Windows device context and includes dozens of member functions for drawing to screens, printers, and other devices. In Windows, all graphical output is performed through device context objects that abstract the physical destinations for output. CPaintDC is a special case of CDC that is used only in WM_PAINT message handlers. Before drawing in response to a WM_PAINT message, an application must call the Windows ::BeginPaint API function to obtain a device context and prepare the device context for painting. When it's finished painting, the application must call ::EndPaint to release the device context and inform Windows that painting is complete. If an application fails to call ::BeginPaint and ::EndPaint when it processes a WM_PAINT message, the message will not be removed from the message queue. Not surprisingly, CPaintDC calls ::BeginPaint from its constructor and ::EndPaint from its destructor to ensure that this doesn't happen.

In MFC, you'll always draw to the screen with a CDC object of some type, but you must use a CPaintDC object only inside OnPaint handlers. Furthermore, it's good practice to create CPaintDC objects on the stack so that their destructors will be called automatically when OnPaint ends. You can instantiate a CPaintDC object with the new operator if you want to, but then it becomes critical to delete that object before OnPaint ends. Otherwise, ::EndPaint won't be called, and your application won't redraw properly.

After creating a CPaintDC object, OnPaint constructs a CRect object representing a rectangle and calls CWnd::GetClientRect to initialize the rectangle with the coordinates of the window's client area:

CRect rect;
GetClientRect (&rect);

OnPaint then calls CDC::DrawText to display "Hello, MFC" in the window's client area:

dc.DrawText (_T ("Hello, MFC"), -1, &rect,
    DT_SINGLELINE ¦ DT_CENTER ¦ DT_VCENTER);

DrawText is a powerful general-purpose function for outputting text. It accepts four parameters: a pointer to the string to display, the number of characters in the string (or -1 if the string is terminated with a NULL character), the address of a RECT structure or CRect object specifying the formatting rectangle (the rectangle in which the string is displayed), and flags specifying output options. In Hello, CMainWindow::OnPaint combines the DT_SINGLELINE, DT_CENTER, and DT_VCENTER flags to display a single line of text that is centered both horizontally and vertically in the formatting rectangle. rect describes the window's client area, so the resulting output is perfectly centered in the window.

Conspicuously missing from DrawText's argument list are parameters specifying basic properties of the output such as the font and text color. These and other characteristics of the output are attributes of the device context and are controlled with CDC member functions such as SelectObject and SetTextColor. Because Hello didn't change any of the device context's attributes, the default font and default text color (black) were used. DrawText also fills a small rectangle surrounding the text it outputs with the device context's current background color. The default is white, so you don't see it if your system's default window background color also happens to be white. But change the window background color to gray and the white text background will stick out like a sore thumb.

In Chapter 2, you'll learn how to customize the output from DrawText and other CDC drawing functions by modifying device context attributes. Once you know how to do it, it's simple to change the text color or tell DrawText to paint the text background with "transparent" pixels.

The Message Map

How is it that a WM_PAINT message from Windows turns into a call to CMainWindow::OnPaint? The answer lies in the message map. A message map is a table that correlates messages and member functions. When Hello's frame window receives a message, MFC scans the window's message map, sees that a handler exists for WM_PAINT messages, and calls OnPaint. The message map is MFC's way of avoiding the lengthy vtables that would be required if every class had a virtual function for every possible message it might receive. Any class derived from CCmdTarget can contain a message map. What MFC does internally to implement message maps is hidden behind some rather complex macros, but using a message map is exceedingly simple. Here's all you have to do to add a message map to a class:

  1. Declare the message map by adding a DECLARE_MESSAGE_MAP statement to the class declaration.

  2. Implement the message map by placing macros identifying the messages that the class will handle between calls to BEGIN_MESSAGE_MAP and END_MESSAGE_MAP.

  3. Add member functions to handle the messages.

Hello's CMainWindow class handles just one message type, WM_PAINT, so its message map is implemented as follows:

BEGIN_MESSAGE_MAP (CMainWindow, CFrameWnd)
    ON_WM_PAINT ()
END_MESSAGE_MAP ()

BEGIN_MESSAGE_MAP begins the message map and identifies both the class to which the message map belongs and the base class. (Message maps are passed by inheritance just as other class members are. The base class name is required so that the framework can find the base class's message map when necessary.) END_MESSAGE_MAP ends the message map. In between BEGIN_MESSAGE_MAP and END_MESSAGE_MAP are the message map entries. ON_WM_PAINT is a macro defined in the MFC header file Afxmsg_.h. It adds an entry for WM_PAINT messages to the message map. The macro accepts no parameters because it is hardcoded to link WM_PAINT messages to the class member function named OnPaint. MFC provides macros for more than 100 Windows messages, ranging from WM_ACTIVATE to WM_WININICHANGE. You can get the name of the message handler that corresponds to a given ON_WM macro from the MFC documentation, but it's fairly easy to deduce the name yourself by replacing WM_ with On and converting all the remaining letters except those at the beginning of the word to lowercase. Thus, WM_PAINT becomes OnPaint, WM_LBUTTONDOWN becomes OnLButtonDown, and so on.

You'll need to consult the MFC documentation to determine what kinds of arguments a message handler receives and what type of value it returns. OnPaint takes no arguments and returns no value, but OnLButtonDown is prototyped like this:

afx_msg void OnLButtonDown (UINT nFlags, CPoint point)

nFlags contains bit flags specifying the state of the mouse buttons and the Ctrl and Shift keys, and point identifies the location at which the click occurred. The arguments passed to a message handler come from the wParam and lParam parameters that accompanied the message. But whereas wParam and lParam are of necessity generic, the parameters passed to an MFC message handler are both specific and type-safe.

What happens if you want to process a message for which MFC doesn't provide a message-map macro? You can create an entry for the message using the generic ON_MESSAGE macro, which accepts two parameters: the message ID and the address of the corresponding class member function. The following statement maps WM_SETTEXT messages to a member function named OnSetText:

ON_MESSAGE (WM_SETTEXT, OnSetText)

OnSetText would be declared like this:

afx_msg LRESULT OnSetText (WPARAM wParam, LPARAM lParam);

Other special-purpose message-map macros provided by MFC include ON_COMMAND, which maps menu selections and other UI events to class member functions, and ON_UPDATE_COMMAND_UI, which connects menu items and other UI objects to "update handlers" that keep them in sync with the internal state of the application. You'll be introduced to these and other message-map macros in the chapters that follow.

Getting back to Hello for a moment, CMainWindow's OnPaint function and message map are declared with the following statements in Hello.h:

afx_msg void OnPaint ();
DECLARE_MESSAGE_MAP ()

afx_msg is a visual reminder that OnPaint is a message handler. You can omit it if you'd like because it reduces to white space when compiled. The term afx_msg is meant to connote a function that behaves as if it were a virtual function but does so without requiring a vtable entry. DECLARE_MESSAGE_MAP is usually the final statement in the class declaration because it uses C++ keywords to specify the visibility of its members. You can follow DECLARE_MESSAGE_MAP with statements declaring other class members, but if you do, you should also lead off with a public, protected, or private keyword to ensure the visibility you want for those members.

How Message Maps Work

You can find out how message maps work by examining the DECLARE_MESSAGE_MAP, BEGIN_MESSAGE_MAP, and END_MESSAGE_MAP macros in Afxwin.h and the code for CWnd::WindowProc in Wincore.cpp. Here's a synopsis of what goes on under the hood when you use message-mapping macros in your code, and how the framework uses the code and data generated by the macros to convert messages into calls to corresponding class member functions.

MFC's DECLARE_MESSAGE_MAP macro adds three members to the class declaration: a private array of AFX_MSGMAP_ENTRY structures named _messageEntries that contains information correlating messages and message handlers; a static AFX_MSGMAP structure named messageMap that contains a pointer to the class's _messageEntries array and a pointer to the base class's messageMap structure; and a virtual function named GetMessageMap that returns messageMap's address. (The macro implementation is slightly different for an MFC application that's dynamically rather than statically linked to MFC, but the principle is the same.) BEGIN_MESSAGE_MAP contains the implementation for the GetMessageMap function and code to initialize the messageMap structure. The macros that appear between BEGIN_MESSAGE_MAP and END_MESSAGE_MAP fill in the _messageEntries array, and END_MESSAGE_MAP marks the end of the array with a NULL entry. For the statements

// In the class declaration
DECLARE_MESSAGE_MAP ()

// In the class implementation
BEGIN_MESSAGE_MAP (CMainWindow, CFrameWnd)
    ON_WM_PAINT ()
END_MESSAGE_MAP ()

the compiler's preprocessor generates this:

// In the class declaration
private:
    static const AFX_MSGMAP_ENTRY _messageEntries[];
protected:
    static const AFX_MSGMAP messageMap;
    virtual const AFX_MSGMAP* GetMessageMap() const;

// In the class implementation
const AFX_MSGMAP* CMainWindow::GetMessageMap() const
    { return &CMainWindow::messageMap; }

const AFX_MSGMAP CMainWindow::messageMap = {
    &CFrameWnd::messageMap,
    &CMainWindow::_messageEntries[0]
};

const AFX_MSGMAP_ENTRY CMainWindow::_messageEntries[] = {
    { WM_PAINT, 0, 0, 0, AfxSig_vv,
        (AFX_PMSG)(AFX_PMSGW)(void (CWnd::*)(void))OnPaint },
    {0, 0, 0, 0, AfxSig_end, (AFX_PMSG)0 }
};

With this infrastructure in place, the framework can call GetMessageMap to get a pointer to CMainWindow's messageMap structure. It can then scan the _messageEntries array to see if CMainWindow has a handler for the message, and if necessary it can grab a pointer to CFrameWnd's messageMap structure and scan the base class's message map, too.

That's a pretty good description of what happens when a message for CMainWindow arrives. To dispatch the message, the framework calls the virtual WindowProc function that CMainWindow inherits from CWnd. WindowProc calls OnWndMsg, which in turn calls GetMessageMap to get a pointer to CMainWindow::messageMap and searches CMainWindow::_messageEntries for an entry whose message ID matches the ID of the message that is currently awaiting processing. If the entry is found, the corresponding CMainWindow function (whose address is stored in the _messageEntries array along with the message ID) is called. Otherwise, OnWndMsg consults CMainWindow::messageMap for a pointer to CFrameWnd::messageMap and repeats the process for the base class. If the base class doesn't have a handler for the message, the framework ascends another level and consults the base class's base class, systematically working its way up the inheritance chain until it finds a message handler or passes the message to Windows for default processing. Figure 1-5 illustrates CMainWindow's message map schematically and shows the route that the framework travels as it searches for a handler to match a given message ID, beginning with the message map entries for CMainWindow.

What MFC's message-mapping mechanism amounts to is a very efficient way of connecting messages to message handlers without using virtual functions. Virtual functions are not space-efficient because they require vtables, and vtables consume memory even if the functions in them are not overridden. The amount of memory used by a message map, in contrast, is proportional to the number of entries it contains. Since it's extremely rare for a programmer to implement a window class that includes handlers for all of the different message types, message mapping conserves a few hundred bytes of memory just about every time a CWnd is wrapped around an HWND.

Click to view at full size.

Figure 1-5. Message-map processing.

Windows, Character Sets, and the _T Macro

Microsoft Windows 98 and Microsoft Windows NT use two different character sets to form characters and strings. Windows 98 and its predecessors use the 8-bit ANSI character set, which is similar to the ASCII character set familiar to many programmers. Windows NT and Windows 2000 use the 16-bit Unicode character set, which is a superset of the ANSI character set. Unicode is ideal for applications sold in international markets because it contains a rich assortment of characters from non-U.S. alphabets. Programs compiled with ANSI characters will run on Windows NT and Windows 2000, but Unicode programs run slightly faster because Windows NT and Windows 2000 don't have to perform an ANSI-to-Unicode conversion on every character. Unicode applications won't run on Windows 98, period, unless you convert every character string passed to Windows from Unicode to ANSI format.

When an application is compiled, it is compiled to use either ANSI or Unicode characters. If your application will be deployed on both Windows 98 and Windows 2000, it may behoove you to make strings character set neutral. Then, by making a simple change to the project's build settings or adding a #define to a header file, you can tell the compiler whether to produce an ANSI build or a Unicode build. If you encode a string literal like this:

"Hello"

the compiler forms the string from ANSI characters. If you declare the string like this:

L"Hello"

the compiler uses Unicode characters. But if you use MFC's _T macro, like this:

_T ("Hello")

the compiler will emit Unicode characters if the preprocessor symbol _UNICODE is defined, and ANSI characters if it is not. If all your string literals are declared with _T macros, you can produce a special Windows NT_only build of your application by defining _UNICODE. Defining this symbol implicitly defines a related symbol named UNICODE (no underscore), which selects the Unicode versions of the numerous Windows API functions that come in both ANSI and Unicode versions. Of course, if you'd like the same executable to run on either platform and you're not concerned about the performance hit an ANSI application incurs under Windows NT, you can forget about the _T macro. I'll use _T throughout this book to make the sample code character set neutral.

Is wrapping string literals in _T macros sufficient to make an application completely agnostic with regard to character sets? Not quite. You must also do the following:

  • Declare characters to be of type TCHAR rather than char. If the _UNICODE symbol is defined, TCHAR evaluates to wchar_t, which is a 16-bit Unicode character. If _UNICODE is not defined, TCHAR becomes plain old char.

  • Don't use char* or wchar_t* to declare pointers to TCHAR strings. Instead, use TCHAR* or, better yet, the LPTSTR (pointer to TCHAR string) and LPCTSTR (pointer to const TCHAR string) data types.

  • Never assume that a character is only 8 bits wide. To convert a buffer length expressed in bytes to a buffer size in characters, divide the buffer length by sizeof(TCHAR).

  • Replace calls to string functions in the C run-time library (for example, strcpy) with the corresponding macros in the Windows header file Tchar.h (for example, _tcscpy).

Consider the following code snippet, which uses the ANSI character set:

char szMsg[256];
pWnd->GetWindowText (szMsg, sizeof (szMsg));
strcat (szMsg, " is the window title");
MessageBox (szMsg);

Here's what the same code would look like if it were revised to be character set neutral:

TCHAR szMsg[256];
pWnd->GetWindowText (szMsg, sizeof (szMsg) / sizeof (TCHAR));
_tcscat (szMsg, _T (" is the window title"));
MessageBox (szMsg);

The revised code uses the generic TCHAR data type, it makes no assumptions about the size of a character, and it uses the TCHAR-compatible string-concatenation function _tcscat in lieu of the more common but ANSI character set_dependent strcat.

There's more that could be said about ANSI/Unicode compatibility, but these are the essentials. For additional information, refer to the online documentation that comes with Visual C++ or to Jeffrey Richter's Advanced Windows (1997, Microsoft Press), which contains an excellent chapter on Unicode and a handy table listing the string macros defined in Tchar.h and their C run-time counterparts.

Building the Application

The CD in the back of this book contains everything you need to use the Hello program in Visual C++. The folder named /Chap01/Hello contains the program's source code as well as the files that make up a Visual C++ project. To open the project, simply select Open Workspace from Visual C++'s File menu and open Hello.dsw. If you modify the application and want to rebuild it, select Build Hello.exe from the Build menu.

You don't have to use the Hello files on the CD. If you'd prefer, you can create your own project and type in the source code. Here are step-by-step instructions for creating a new project in Visual C++ 6:

  1. Select New from the Visual C++ File menu, and click the Projects tab to go to the Projects page.

  2. Select Win32 Application, and enter a project name in the Project Name text box. If desired, you can change the path name—the drive and folder where the project and its source code will be stored—in the Location text box. Then click OK.

  3. In the Win32 Application window, select An Empty Project and then click Finish.

  4. Add source code files to the project. To enter a source code file from scratch, select New from the File menu, select the file type, and enter the file name. Be sure the Add To Project box is checked so that the file will be added to the project. Then click OK, and edit the file as you see fit. To add an existing source code file to a project, go to the Project menu, select Add To Project and then Files, and pick the file.

  5. Select Settings from the Project menu. In the Project Settings dialog box, be sure that the project name is selected in the left pane and then click the General tab if the General page isn't already displayed. Select Use MFC In A Shared DLL from the drop-down list labeled Microsoft Foundation Classes, and then click OK to register the change with Visual C++.

Choosing Use MFC In A Shared DLL minimizes your application's executable file size by allowing MFC to be accessed from a DLL. If you choose Use MFC In A Static Library instead, Visual C++ links MFC code into your application's EXE file and the file size grows considerably. Static linking uses disk space less efficiently than dynamic linking because a hard disk containing 10 statically linked MFC applications contains 10 copies of the same MFC library code. On the other hand, an application that is statically linked can be run on any PC, whether or not the MFC DLL is present. It's your call whether to link to MFC statically or dynamically, but remember that if you distribute a dynamically linked EXE, you'll need to distribute the DLL that houses MFC, too. For a release-build MFC application created with Visual C++ version 6, that DLL is named Mfc42.dll if the program uses ANSI characters and Mfc42u.dll if it uses Unicode characters.

The Big Picture

Before we move on, let's pause for a moment and review some of the important concepts learned from the Hello application. The very first thing that happens when the application is started is that a globally scoped application object is created. MFC's AfxWinMain function calls the application object's InitInstance function. InitInstance constructs a window object, and the window object's constructor creates the window that appears on the screen. After the window is created, InitInstance calls the window's ShowWindow function to make it visible and UpdateWindow to send it its first WM_PAINT message. Then InitInstance returns, and AfxWinMain calls the application object's Run function to start the message loop. WM_PAINT messages are converted by MFC's message-mapping mechanism into calls to CMainWindow::OnPaint, and OnPaint draws the text "Hello, MFC" in the window's client area by creating a CPaintDC object and calling its DrawText function.

If you're coming to MFC straight from the Windows SDK, this probably seems like a pretty strange way to do business. Two-step window creation? Application objects? No more WinMain? It's definitely different from the way Windows used to be programmed. But compare Hello's source code to the C program listing back in Figure 1-2, and you'll find that MFC undeniably simplifies things. MFC doesn't necessarily make the source code easier to understand—after all, Windows programming is still Windows programming—but by moving a lot of the boilerplate stuff out of the source code and into the class library, MFC reduces the amount of code you have to write. That, combined with the fact that you can modify the behavior of any MFC class by deriving from it a class of your own, makes MFC an effective tool for programming Windows. The benefits will really become apparent when you begin tapping into some of the more sophisticated features of Windows or building ActiveX controls and other Windows-based software components. With MFC, you can get an ActiveX control up and running in nothing flat. Without it—well, good luck.

Hello lacks many of the elements that characterize a full-blown Windows program, but it's still a good first step on the road to becoming an MFC programmer. In subsequent chapters, you'll learn about menus, dialog boxes, and other components of an application's user interface. You'll also see how Windows programs read input from the mouse and keyboard and learn more about drawing in a window. Chapter 2 leads off by introducing some additional CDC drawing functions and demonstrating how to add scroll bars to a frame window so that you can view a workspace larger than the window's client area. Both are essential next steps in building the knowledge base required to become a Windows programmer.

WinUI3入门指南:从零构建现代化Windows桌面应用 在Windows桌面应用开发领域,UI框架的演进始终是开发者关注的核心。从传统的WinForms、WPF到现代的UWP,微软不断推动着开发体验的革新。WinUI3作为新一代原生UI框架,其核心原理在于实现了UI框架与操作系统版本的解耦,通过NuGet包独立更新,解决了长期困扰开发者的系统依赖问题。这一技术变革为Windows应用带来了显著的工程价值:开发者可以更灵活地采用现代化设计语言,同时保持与现有.NET生态的紧密集成。在实际应用场景中,无论是需要应用商店分发的打包应用,还是追求部署灵活性的非打包应用, 阅读详情

相关推荐

【202503】Wan:开放且先进的大规模视频生成模型【1.3B、14B】【支持对无限长度视频进行稳定的Inference】【Wan中的主要计算开销来自注意力机制】

wan: Open and Advanced Large-Scale Video Generative ModelsWan:开放且先进的大规模视频生成模型Wan Team, Alibaba Group Wan 团队,Alibaba GroupThis report presents Wan, a comprehensive and open suite of video foundation models designed to push the boundaries of video generation

u013250861的博客 782

C++/C#通过进程ID查找对应窗口句柄

C++/C#查找窗口句柄-记一次通过进程ID查找对应窗口句柄 FindWindowEx EnumWindows MoveWindow GetWindowThreadProcessId GetClassName

jiaodou2的博客 7952

MFCApplication1.rar

基于VS2017+MFC对话框设计子对话框的简单操作,实现通过按钮打开三个子对话框,后续可以进行其他处理行为。

【Windows】UWP - Application Frame 窗口句柄溯源

当 GUI 线程的窗口属于 Windows/UWP 应用程序时,它们始终由进程 ApplicationFrameHost 托管。如果依然使用 Win32 的那套方法我们最终将获取到根进程ApplicationFrameHost.exe 而不是实际的 AppContainer 进程或者 RuntimeBroker 进程。

溡漪幽博客 2386

AnyGrasp实战指南:从环境配置到抓取检测与跟踪

本文详细介绍了AnyGrasp从环境配置到抓取检测与跟踪的实战指南。涵盖硬件要求、关键依赖安装避坑、抓取检测与跟踪的实战技巧,以及常见问题解决方案和性能优化建议,帮助开发者快速掌握这一高精度物体抓取检测与跟踪技术。

weixin_33712987的博客 283

2025-E题国一-简易自行瞄准装置:基于嘉立创地猛星/天猛星与K230的视觉巡线云台系统设计

本文详细介绍了2025年全国大学生电子设计竞赛E题一等奖作品——基于嘉立创地猛星/天猛星与K230的视觉巡线云台系统设计。该系统通过地猛星主控实现小车巡线,天猛星主控驱动云台,结合K230开发板的视觉识别能力,构建了一套完整的视觉巡线云台系统,实现了自动巡线与精准瞄准功能。文章深入剖析了硬件选型、双闭环PID控制算法、视觉识别与目标跟踪等核心技术,并分享了系统调试与避坑经验。

weixin_42596011的博客 681

Python----pywin32如何获取窗口句柄

Python----pywin32如何获取窗口句柄一:介绍要用到的库二:显示窗口的属性1. 获取所有窗口的句柄2.获取窗口的子窗口句柄3.获取句柄的标题4.获取窗口类名三、实际操作1.置顶和取消2.显示和隐藏窗口四、案例演示显示和隐藏托盘 halo,各位读者,本栏目开设一个围绕着“如何用Python来制作PC软件”展开。 当我们想用处理Windows的软件窗口时,常常会碰到想将窗口置顶、隐藏和显示等等,还有读者想将电脑托盘、任务栏等都隐藏的情况。本篇文章就是带领读者学习窗口句柄,并且如何应用Python带的

qq_39369520的博客 2万+

【论文阅读1】机理引导的残差学习用于电池全生命周期状态监测 | Nature Communications

本文提出了一种机理引导的残差学习框架,用于提升电池全生命周期内荷电状态(SOC)和健康状态(SOH)的监测精度。该方法融合等效电路模型的先验知识与机器学习,设计了修正模型和补偿模型两种通用框架。实验验证表明,该方法在三种不同类型电池数据集上均表现出色,SOC和SOH估计误差较传统方法降低50%以上,且在未见工况下仍保持良好外推能力。模型具有强鲁棒性,在减少训练数据量和降低采样频率时性能稳定,并兼具物理可解释性。该框架无需离线测试和运行中校准,为电池安全监测提供了有效解决方案。

qq_21843433的博客 618

AutoHotKey自动热键(四)WINDOWS程序窗口的9种匹配方法与Window Spy窗口检索的使用方法

我们在进行窗口匹配的时候,根据匹配类型的不同可以多种匹配方法,根据使用者目录中可以找到九种匹配方式,这些匹配方式大都需自带的SPY监视工具用以查看窗口的名称.类名.进程名.句柄ID.位置信息等等。

weixin_43716462的博客 4570

Abel逆变换及其求解方法

Abel逆变换常应用在轴对称的、光学薄的火焰、羽流或等离子体重建。

weixin_49783507的博客 8400

Win32 Application基本框架

//程序入口 intAPIENTRY WinMain(HINSTANCE hInstance,                                              HINSTANCE hPrevInstance,                                               LPSTR lpCmdLine,

梦想博客 1537

运算放大器 VS 仪表放大器

运算放大器(Operational Amplifier, 简称 Op Amp)和仪表放大器(Instrumentation Amplifier, 简称INA)在电子电路设计中都有非常广泛的应用,但两者在结构、特性以及应用场景上都有明显的区别。以下是它们之间主要的差异:运算放大器(Op Amp)仪表放大器(INA)运算放大器仪表放大器运算放大器仪表放大器运算放大器仪表放大器运算放大器仪表放大器总之,运算放大器是通用型放大元件,需要设计者自己做额外的电路配置;而仪表放大器则是针对高精度测量差分信号而生,内部匹配

chinahongjiang的博客 1353

MFC Application---The Frame Window Object (转)

MFC Application---The Frame Window Object (转)[@more@] The Frame Window object MFC's CWnd class and its derivat...

ciya3282的博客 159

Pandas滚动窗口的妙用:动态计算列数据的最大值

Pandas的滚动窗口(rolling window)功能是数据分析中处理时间序列数据的重要工具。本文通过实例演示了如何使用rolling(window=4).max()计算DataFrame列A的滚动最大值,并将结果存入新列Max_Range。该方法会在4个元素的滑动窗口内计算最大值,前3行因数据不足显示为NaN。这种技术广泛应用于金融分析(如股价波动)、数据平滑和趋势识别等场景,能有效帮助分析数据的动态变化特征。示例展示了从数据准备到结果输出的完整流程,体现了Pandas在处理滑动窗口计算时的高效性和便

m0_74337424的博客 58

10年上位机开发踩过的20个坑:C#通信/线程/UI适配避坑指南

通信层:所有通信操作异步化、异常全覆盖,加断线重连+心跳检测,多设备隔离资源;线程层:UI更新必做跨线程判断,共享数据加锁,线程池限流,异常不静默;UI层:适配高分屏/DPI,用布局容器替代固定坐标,多屏场景绑定主屏幕。

这里只有干货:从 Modbus 通信到 MES 对接,从 YOLO 训练到工控机部署,带你搞定工业软件开发全流程。 914

VC++ 6.0深度解析:从MFC框架到遗留系统维护实战

C++作为面向对象编程的核心语言,其编译链接机制和内存管理原理是构建大型软件系统的基石。在Windows平台开发中,理解底层API调用和框架设计对于开发高性能、高稳定性应用程序至关重要。MFC(Microsoft Foundation Classes)框架作为早期Windows C++开发的事实标准,通过文档/视图架构和消息映射机制,极大地提升了GUI应用程序的开发效率。对于工业控制、嵌入式上位机等领域的遗留系统,掌握VC++ 6.0这一经典开发环境,不仅能深入理解PE文件格式、多线程同步等底层技术,更能实

weixin_33853827的博客 393

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

Windows API 函数

《Windows API函数手册》摘要 本文档是Windows平台开发的权威参考手册,全面收录774个核心API函数,涵盖系统管理、进程线程、窗口消息、文件操作、图形处理等12大功能模块。手册采用结构化编排,主要特点包括: 编码规范 详细区分多字节(char)与宽字符(wchar_t)编码体系 提供LPSTR/LPCWSTR等字符串指针类型的完整解析 说明UTF-8与GBK编码转换的实际应用场景 核心功能模块 窗口创建:完整展示从注册类到消息循环的窗口生命周期 文件操作:覆盖CreateFile/ReadF

gqk01的博客 867

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

泽众AutoRunner软件的使用方法,以测试win10环境下系统自带的计算器为例

用AutoRunner在win10测试系统自带的计算器,含操作动态图,及新手常见错误

你个无聊小demo的博客 1万+

MFC Application

Your First MFC ApplicationIts time to build your first MFC application. And what better place to start than with one that displays "Hello, MFC" in a window? Based on the classic "Hello, world" prog

lemonade的专栏 3640

ApplicationFrame详细简介

        import   org.jfree.ui.ApplicationFrame     是界面方面的类       其实它就只是一个窗口类      即public Frame(String title) throws HeadlessException      下面贴出它的原代码package org.jfree.ui;import java.awt.even

zhou2002的专栏 3352

there is no source code available for the current location 解决方案

1.首先试最常规的方法:Clean and then rebuild solution,但是没有解决 2.进入Tools>Options,选择Debugging>General 却掉 Enable address-level debugging 选项,在去掉 Require source files to exactly match the original version. Ok...

weixin_34138521的博客 278

window和frame的用法

window.top、window.parent与window.opener的区别 top: 该变更永远指分割窗口最高层次的浏览器窗口。 如果计划从分割窗口的最高层次开始执行命令,就可以用top变量。 parent: 该变量指的是包含当前分割窗口的父窗口。 如果在一个窗口内有分割窗口,而在其中一个分割窗口中又包含着分割窗口,则第2层的分割窗口可以用parent变量引用包含它的父分割窗...

menghuanzhiming的博客 5371

frame 和window的区别

frame 和window,window包括frame,window一定是整个屏幕,而frame可以是整个屏幕,也可以不是整个屏幕。

gaoyangliu的博客 4097
上一篇: MFC Application
下一篇: Moving the Origin
lemonade
博客等级 码龄26年 8粉丝 33原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值