- Changing the Styles of a Window Created by MFC
- Changing Styles in a New MFC Application
- Changing Styles in an Existing Application
- The SDI Case
- The MDI Case
- Изменение стилей окна, созданного MFC Changing the Styles of a Window Created by MFC
- Изменение стилей в новом приложении MFC Changing Styles in a New MFC Application
- Изменение стилей в существующем приложении Changing Styles in an Existing Application
- Вариант SDI The SDI Case
- Вариант MDI The MDI Case
- SetWindowLongW function (winuser.h)
- Syntax
- Parameters
- Return value
- Remarks
- Examples
Changing the Styles of a Window Created by MFC
In its version of the WinMain function, MFC registers several standard window classes for you. Because you don’t normally edit MFC’s WinMain , that function gives you no opportunity to change the MFC default window styles. This article explains how you can change the styles of such a preregistered window class in an existing application.
Changing Styles in a New MFC Application
If you’re using Visual C++ 2.0 or later, you can change the default window styles in the Application Wizard when you create your application. In the Application Wizard’s User Interface Features page, you can change styles for your main frame window and MDI child windows. For either window type, you can specify its frame thickness (thick or thin) and any of the following:
Whether the window has Minimize or Maximize controls.
Whether the window appears initially minimized, maximized, or neither.
For main frame windows, you can also specify whether the window has a System Menu. For MDI child windows, you can specify whether the window supports splitter panes.
Changing Styles in an Existing Application
If you’re changing window attributes in an existing application, follow the instructions in the rest of this article instead.
To change the default window attributes used by a framework application created with the Application Wizard, override the window’s PreCreateWindow virtual member function. PreCreateWindow allows an application to access the creation process normally managed internally by the CDocTemplate class. The framework calls PreCreateWindow just prior to creating the window. By modifying the CREATESTRUCT structure passed to PreCreateWindow , your application can change the attributes used to create the window. For example, to ensure that a window does not use a caption, use the following bitwise operation:
The CTRLBARS sample application demonstrates this technique for changing window attributes. Depending on what your application changes in PreCreateWindow , it may be necessary to call the base class implementation of the function.
The following discussion covers the SDI case and the MDI case.
The SDI Case
In a single document interface (SDI) application, the default window style in the framework is a combination of the WS_OVERLAPPEDWINDOW and FWS_ADDTOTITLE styles. FWS_ADDTOTITLE is an MFC-specific style that instructs the framework to add the document title to the window’s caption. To change the window attributes in an SDI application, override the PreCreateWindow function in your class derived from CFrameWnd (which the Application Wizard names CMainFrame ). For example:
This code creates a main frame window without Minimize and Maximize buttons and without a sizable border. The window is initially centered on the screen.
The MDI Case
A little more work is required to change the window style of a child window in a multiple document interface (MDI) application. By default, an MDI application created with the Application Wizard uses the default CMDIChildWnd class defined in MFC. To change the window style of an MDI child window, you must derive a new class from CMDIChildWnd and replace all references to CMDIChildWnd in your project with references to the new class. Most likely, the only reference to CMDIChildWnd in the application is located in your application’s InitInstance member function.
The default window style used in an MDI application is a combination of the WS_CHILD, WS_OVERLAPPEDWINDOW, and FWS_ADDTOTITLE styles. To change the window attributes of an MDI application’s child windows, override the PreCreateWindow function in your class derived from CMDIChildWnd . For example:
This code creates MDI child windows without a Maximize button.
Изменение стилей окна, созданного MFC Changing the Styles of a Window Created by MFC
В своей версии WinMain функции MFC регистрирует несколько стандартных классов окон. In its version of the WinMain function, MFC registers several standard window classes for you. Так как обычно не редактируется MFC WinMain , эта функция не позволяет изменять стили окон по умолчанию для MFC. Because you don’t normally edit MFC’s WinMain , that function gives you no opportunity to change the MFC default window styles. В этой статье объясняется, как можно изменить стили такого класса с предварительно зарегистрированным окном в существующем приложении. This article explains how you can change the styles of such a preregistered window class in an existing application.
Изменение стилей в новом приложении MFC Changing Styles in a New MFC Application
Если вы используете Visual C++ 2,0 или более поздней версии, вы можете изменить стили окна по умолчанию в мастере приложений при создании приложения. If you’re using Visual C++ 2.0 or later, you can change the default window styles in the Application Wizard when you create your application. На странице функций пользовательского интерфейса мастера приложений можно изменить стили для основного окна фрейма и дочерних окон MDI. In the Application Wizard’s User Interface Features page, you can change styles for your main frame window and MDI child windows. Для любого типа окна можно указать толщину фрейма (толстую или тонкую) и любой из следующих элементов: For either window type, you can specify its frame thickness (thick or thin) and any of the following:
Содержит ли окно элементы управления «Minimize» или «развернуто». Whether the window has Minimize or Maximize controls.
Отображается ли окно изначально в режиме сворачивания, развернуто или ни на один. Whether the window appears initially minimized, maximized, or neither.
В окнах главного фрейма можно также указать, имеется ли в окне Системное меню. For main frame windows, you can also specify whether the window has a System Menu. Для дочерних окон MDI можно указать, поддерживает ли окно панели разделения. For MDI child windows, you can specify whether the window supports splitter panes.
Изменение стилей в существующем приложении Changing Styles in an Existing Application
Если вы изменяете атрибуты окна в существующем приложении, следуйте инструкциям, приведенным в оставшейся части этой статьи. If you’re changing window attributes in an existing application, follow the instructions in the rest of this article instead.
Чтобы изменить атрибуты окна по умолчанию, используемые приложением платформы, созданным с помощью мастера приложений, переопределите виртуальную функцию-член PreCreateWindow окна. To change the default window attributes used by a framework application created with the Application Wizard, override the window’s PreCreateWindow virtual member function. PreCreateWindow позволяет приложению получить доступ к процессу создания, обычно управляемому классом CDocTemplate . PreCreateWindow allows an application to access the creation process normally managed internally by the CDocTemplate class. Платформа вызывает PreCreateWindow непосредственно перед созданием окна. The framework calls PreCreateWindow just prior to creating the window. Изменяя структуру CREATESTRUCT , переданную в PreCreateWindow , приложение может изменять атрибуты, используемые для создания окна. By modifying the CREATESTRUCT structure passed to PreCreateWindow , your application can change the attributes used to create the window. Например, чтобы убедиться, что в окне не используется заголовок, используйте следующую побитовую операцию: For example, to ensure that a window does not use a caption, use the following bitwise operation:
Пример приложения CTRLBARS демонстрирует этот метод для изменения атрибутов окна. The CTRLBARS sample application demonstrates this technique for changing window attributes. В зависимости от того, что приложение изменяет в PreCreateWindow , может потребоваться вызов реализации функции в базовом классе. Depending on what your application changes in PreCreateWindow , it may be necessary to call the base class implementation of the function.
В следующем обсуждении рассматривается вариант использования SDI и MDI. The following discussion covers the SDI case and the MDI case.
Вариант SDI The SDI Case
В приложении с одним документом (SDI) стиль окна по умолчанию в платформе является сочетанием стилей WS_OVERLAPPEDWINDOW и FWS_ADDTOTITLE . In a single document interface (SDI) application, the default window style in the framework is a combination of the WS_OVERLAPPEDWINDOW and FWS_ADDTOTITLE styles. FWS_ADDTOTITLE является стилем MFC, который указывает платформе добавить заголовок документа в заголовок окна. FWS_ADDTOTITLE is an MFC-specific style that instructs the framework to add the document title to the window’s caption. Чтобы изменить атрибуты окна в приложении SDI, переопределите PreCreateWindow функцию в классе, производную от CFrameWnd (имя мастера приложений CMainFrame ). To change the window attributes in an SDI application, override the PreCreateWindow function in your class derived from CFrameWnd (which the Application Wizard names CMainFrame ). Пример: For example:
Этот код создает главное окно фрейма без кнопок сворачивания и развертывания и без изменяемой границы. This code creates a main frame window without Minimize and Maximize buttons and without a sizable border. Изначально окно располагается по центру экрана. The window is initially centered on the screen.
Вариант MDI The MDI Case
Для изменения стиля окна дочернего окна в приложении многодокументного интерфейса (MDI) требуется немного больше работы. A little more work is required to change the window style of a child window in a multiple document interface (MDI) application. По умолчанию приложение MDI, созданное с помощью мастера приложений, использует класс CMDIChildWnd по умолчанию, определенный в MFC. By default, an MDI application created with the Application Wizard uses the default CMDIChildWnd class defined in MFC. Чтобы изменить стиль окна дочернего окна MDI, необходимо создать новый класс из CMDIChildWnd и заменить все ссылки на CMDIChildWnd в проекте ссылками на новый класс. To change the window style of an MDI child window, you must derive a new class from CMDIChildWnd and replace all references to CMDIChildWnd in your project with references to the new class. Скорее всего, единственная ссылка на CMDIChildWnd приложение находится в InitInstance функции-члене приложения. Most likely, the only reference to CMDIChildWnd in the application is located in your application’s InitInstance member function.
Стиль окна по умолчанию, используемый в приложении MDI, является сочетанием стилей WS_CHILD, WS_OVERLAPPEDWINDOW и FWS_ADDTOTITLE . The default window style used in an MDI application is a combination of the WS_CHILD, WS_OVERLAPPEDWINDOW, and FWS_ADDTOTITLE styles. Чтобы изменить атрибуты окна дочерних окон приложения MDI, переопределите функцию PreCreateWindow в классе, производном от CMDIChildWnd . To change the window attributes of an MDI application’s child windows, override the PreCreateWindow function in your class derived from CMDIChildWnd . Пример: For example:
Этот код создает дочерние MDI-окна без кнопки развертывания. This code creates MDI child windows without a Maximize button.
SetWindowLongW function (winuser.h)
Changes an attribute of the specified window. The function also sets the 32-bit (long) value at the specified offset into the extra window memory.
Syntax
Parameters
A handle to the window and, indirectly, the class to which the window belongs.
The zero-based offset to the value to be set. Valid values are in the range zero through the number of bytes of extra window memory, minus the size of an integer. To set any other value, specify one of the following values.
Value | Meaning | ||||||||
---|---|---|---|---|---|---|---|---|---|
GWL_EXSTYLE -20 | Sets a new extended window style. | ||||||||
GWL_HINSTANCE -6 | Sets a new application instance handle. | ||||||||
GWL_ID -12 | Sets a new identifier of the child window. The window cannot be a top-level window. | ||||||||
GWL_STYLE -16 | Sets a new window style. | ||||||||
GWL_USERDATA -21 | Sets the user data associated with the window. This data is intended for use by the application that created the window. Its value is initially zero. | ||||||||
GWL_WNDPROC -4 | Sets a new address for the window procedure. You cannot change this attribute if the window does not belong to the same process as the calling thread. The following values are also available when the hWnd parameter identifies a dialog box.
The replacement value. Return valueIf the function succeeds, the return value is the previous value of the specified 32-bit integer. If the function fails, the return value is zero. To get extended error information, call GetLastError. If the previous value of the specified 32-bit integer is zero, and the function succeeds, the return value is zero, but the function does not clear the last error information. This makes it difficult to determine success or failure. To deal with this, you should clear the last error information by calling SetLastError with 0 before calling SetWindowLong. Then, function failure will be indicated by a return value of zero and a GetLastError result that is nonzero. RemarksCertain window data is cached, so changes you make using SetWindowLong will not take effect until you call the SetWindowPos function. Specifically, if you change any of the frame styles, you must call SetWindowPos with the SWP_FRAMECHANGED flag for the cache to be updated properly. If you use SetWindowLong with the GWL_WNDPROC index to replace the window procedure, the window procedure must conform to the guidelines specified in the description of the WindowProc callback function. If you use SetWindowLong with the DWL_MSGRESULT index to set the return value for a message processed by a dialog procedure, you should return TRUE directly afterward. Otherwise, if you call any function that results in your dialog procedure receiving a window message, the nested window message could overwrite the return value you set using DWL_MSGRESULT. Calling SetWindowLong with the GWL_WNDPROC index creates a subclass of the window class used to create the window. An application can subclass a system class, but should not subclass a window class created by another process. The SetWindowLong function creates the window subclass by changing the window procedure associated with a particular window class, causing the system to call the new window procedure instead of the previous one. An application must pass any messages not processed by the new window procedure to the previous window procedure by calling CallWindowProc. This allows the application to create a chain of window procedures. Reserve extra window memory by specifying a nonzero value in the cbWndExtra member of the WNDCLASSEX structure used with the RegisterClassEx function. You must not call SetWindowLong with the GWL_HWNDPARENT index to change the parent of a child window. Instead, use the SetParent function. If the window has a class style of CS_CLASSDC or CS_OWNDC, do not set the extended window styles WS_EX_COMPOSITED or WS_EX_LAYERED. Calling SetWindowLong to set the style on a progressbar will reset its position. ExamplesThe winuser.h header defines SetWindowLong as an alias which automatically selects the ANSI or Unicode version of this function based on the definition of the UNICODE preprocessor constant. Mixing usage of the encoding-neutral alias with code that not encoding-neutral can lead to mismatches that result in compilation or runtime errors. For more information, see Conventions for Function Prototypes. |