WINAPI CreateWindow Displaying Strange Results - c++

I'm having trouble with a WINAPI project. There are two problems, when I launch a window with the below code, the height parameter behaves strangely. It seems to cap off at 1092, 18 pixels below where I need it on my computer. The second problem is that the window has no edges nor the top menu bar, until I use the Windows+Up/Down key combination to minimize and maximize it, then it behaves normally. I'm using the below code to initialize the window (the only code that runs before this initializes the options.pxXRes and other variables used below):
//Set up the window class
WNDCLASSEX wndClass;
wndClass.cbSize = sizeof(WNDCLASSEX);
wndClass.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
wndClass.lpfnWndProc = &WndHandleInput;
wndClass.cbClsExtra = 0;
wndClass.cbWndExtra = 0;
wndClass.hInstance = GetModuleHandle(nullptr);
wndClass.hIcon = nullptr;
wndClass.hCursor = LoadCursor(nullptr, IDC_ARROW);
wndClass.hbrBackground = (HBRUSH)(COLOR_BACKGROUND + 1);
wndClass.lpszMenuName = nullptr;
wndClass.lpszClassName = "ToastCatClass";
wndClass.hIconSm = nullptr;
RegisterClassEx(&wndClass);
RECT wndRect;
if (options.fullscreen) {
wndRect.left = 0;
wndRect.right = options.pxXRes;
wndRect.top = 0;
wndRect.bottom = options.pxYRes;
AdjustWindowRect(&wndRect, WS_OVERLAPPEDWINDOW, false);
} else {
wndRect.left = (GetPXXRes() - options.pxXRes) / 2;
wndRect.right = options.pxXRes;
wndRect.top = (GetPXYRes() - options.pxYRes) / 2;
wndRect.bottom = options.pxYRes;
AdjustWindowRect(&wndRect, WS_OVERLAPPEDWINDOW, false);
}
hWnd = CreateWindowEx(
0,
wndClass.lpszClassName,
"ToastCat",
WS_OVERLAPPEDWINDOW,
wndRect.left,
wndRect.top,
wndRect.right - wndRect.left,
wndRect.bottom - wndRect.top,
nullptr,
nullptr,
wndClass.hInstance,
nullptr
);
assert(hWnd != nullptr, "Failure to launch window.");
ShowWindow(hWnd, SW_SHOWDEFAULT);
UpdateWindow(hWnd);
The Window procedure is as follows:
LRESULT __stdcall WndHandleInput(HWND hWndParam, UINT msg, WPARAM wParam, LPARAM lParam) {
switch (msg) {
case WM_NCCREATE:
return true;
case WM_KEYDOWN:
switch (wParam) {
//TODO: Update controls
}
break;
case WM_KEYUP:
switch (wParam) {
//TODO: Update controls
}
break;
case WM_CLOSE:
case WM_QUIT:
Cleanup();
break;
default:
return DefWindowProc(hWnd, msg, wParam, lParam);
}
return 0;
}

Windows have two different rectangles:
the client rectangle which is the area of the window to which the application can draw or create child windows within and
the window rectangle which is the outer rectangle of the window (including borders, menu, ...).
By calling AdjustWindowRect you're converting a client rectangle to a window rectangle. Therefore the borders and the menu cannot be visible if you're setting up a client rectangle as big as the entire screen, converting it to a window rectangle and creating a window with such size. If you look at wndRect after the call to AdjustWindowRect(..) using the debugger you will see that top and left are negative.
That the window height is off by some pixels is the default windows behavior. Windows by default does not allow windows to have a height bigger than the screen height because this will move the caption out of the area the mouse can get to. To change this you have to process message WM_GETMINMAXINFO:
case WM_GETMINMAXINFO:
DefWindowProc(hWnd, msg, wParam, lParam);
MINMAXINFO *pmmi = (MINMAXINFO*)lParam;
pmmi->ptMaxTrackSize.x *= 2; // just make it bigger...
pmmi->ptMaxTrackSize.y *= 2; //
return 0;
If you just want to start your window either maximized (with all controls and border visible) or at some other defined location just do the following: Create your window normally with the wndRect initialized within the else-part of if (options.fullscreen) and change the call of ShowWindow(..) as follows:
if (options.fullscreen)
{
ShowWindow(hWnd, SW_MAXIMIZE);
}
else
{
ShowWindow(hWnd, SW_SHOWDEFAULT);
}
UpdateWindow(hWnd);

Related

Painting colored text to c++ win32

Is it possible to paint colored text to what I've already done?
I've tried WM_CTLCOLORSTATIC, CreateSolidBrush(), and several other functions.
//-----------------------------------
// Learning the win32 API for C++
//
// Created by: Cosmic Cruizer
//-----------------------------------
#include <windows.h>
#include <tchar.h>
// Function declarations
bool SetUpWindowClass (char*, int, int, int); // Remove window structure from WinMain and put into function
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM) // Pre-declare Windows procedure/function
// Global variables
const char CLASS_NAME[] = "My Window Class Array"; // declared for window class; Can be static or const
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,LPSTR lpCmdLine, int nCmdShow){
//Step 1: Registering the Window Class
HWND hwnd{}; // This is the handle for our window
MSG msg{}; // Handle for messages to the application
SetUpWindowClass (NULL, NULL, NULL, NULL); // The Window structure - removed from main and made into a function
// Step 2: Creating the Window
hwnd = CreateWindowEx( // returns a handle to the new window, or zero if the function fails
WS_EX_CLIENTEDGE, // Optional window styles. Can be set to 0
CLASS_NAME, // Name of window class, see set 1b. Also set as the constant
"My First C++ Windows App", // Window title text
WS_OVERLAPPEDWINDOW, // Window style, title bar, a border, a system menu, and Minimize and Maximize buttons.
200, 200, 500, 400, // Size and position
NULL, NULL, hInstance, NULL); // Parent window, Menu, Instance handle, Additional app data
// Add an exit button
CreateWindow(
"BUTTON", // Predefined class; Unicode assumed
"EXIT", // Button text
WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, // Styles
200, 200, 60, 25, // x position, y position, Button width, Button height
hwnd, // Parent window
NULL, // No menu.
(HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE), NULL); // Pointer not needed.
ShowWindow(hwnd, nCmdShow); // Make the window visible on the screen
// Step 3: The Message Loop
while(GetMessage(&msg, NULL, 0, 0) != 0) { // Run the message loop. It will run until GetMessage() returns 0
TranslateMessage(&msg); // Translate virtual-key messages into character messages
DispatchMessage(&msg); // Send message to WindowProcedure
}
return msg.wParam;
}
//---------- Functions ----------//
// Setup the window structure
bool SetUpWindowClass (char *cpTitle, int iR, int iG, int iB) {
//Step 1a: The Window structure
WNDCLASSEX wc{}; // Data structure for the windowclass
wc.cbSize = sizeof(WNDCLASSEX); // Sets the size of the Windows API
wc.style = 0; // define additional elements of the window class
wc.lpfnWndProc = WndProc; // defines most of the behavior of the window. See setp 4 "LRESULT CALLBACK WndProc" function
wc.cbClsExtra = 0; // No extra bytes after the window class
wc.cbWndExtra = 0; // structure for the window instance
wc.hInstance = GetModuleHandle (NULL); // handle to the application instance.
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); // handle to icon class, if NULL, system provides a default icon.
wc.hCursor = LoadCursor(NULL, IDC_ARROW); // handle to cursor class
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+18); // Add color as the background of the window
wc.lpszMenuName = NULL; // No menu
wc.lpszClassName = CLASS_NAME; // string that identifies the window class
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
//Step 1b: Register the window class, and if it fails quit the program
if (RegisterClassEx (&wc)) return true;
else return false;
}
// Step 4: the Window Procedure in this function
LRESULT CALLBACK WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam){
switch(uMsg){
case WM_CLOSE:{
DestroyWindow(hwnd);
break;
}
case WM_COMMAND:{ // Close the window when exit is pressed
if (MessageBox(hwnd, "Really quit?", "Exit Warning", MB_OKCANCEL) == IDOK){ // what the hell, just wanted this.
PostQuitMessage(0);
}
break;
}
case WM_DESTROY:{
PostQuitMessage(0);
break;
}
//--- trying to create colored text ---//
case WM_CTLCOLORSTATIC:{
HDC hdcStatic = (HDC) wParam; // handle to display context
hwnd = (HWND) lParam; // handle to control window
SetTextColor(hdcStatic, RGB(100,255,255));
SetBkColor(hdcStatic, RGB(250,250,6));
return (INT_PTR)CreateSolidBrush(RGB(250,250,100));
}
case WM_CTLCOLOREDIT:{
HDC hdcStatic = (HDC) wParam;
SetTextColor(hdcStatic, RGB(0,0,255));
SetBkColor(hdcStatic, RGB(0,230,0));
return (INT_PTR)CreateSolidBrush(RGB(0,230,0));
}
case WM_PAINT:{ // All painting (text) occurs here, between BeginPaint and EndPaint.
PAINTSTRUCT ps; // Holds info about current painting session.
HDC hdc = BeginPaint(hwnd, &ps); // Create the device context (DC)
// Each character is added to the cpaText array. Then the for loop goes through and paints each character
int iY = 7; // Vertical spaces and number of lines for the array
const char *cpaText [iY] = { // changed from char to const char to get rid of warning. and added 1 for each line and a return
"Hello Peoples",
"",
"This is my first attempt to program using the Win32 API.",
"I can only hope it gets better with time.",
"",
"Created by \"The\" Cosmic Cruizer"
};
for (int iLoopCounter = 0; cpaText [iLoopCounter] != 0; iLoopCounter++, iY += 20) {
TextOut (hdc, 5, iY, cpaText [iLoopCounter], strlen (cpaText [iLoopCounter]));
}
EndPaint(hwnd, &ps); // Free up HDC created with BeginPaint
break;
}
default:{
return DefWindowProc(hwnd, uMsg, wParam, lParam); // Return is needed either here or at the end
break;
}
}
return DefWindowProc(hwnd, uMsg, wParam, lParam); // Return is needed either here or in the default case
}
WM_CTLCOLORSTATIC and WM_CTLCOLOREDIT are notification messages used by STATIC/EDIT controls, neither of which you have on your window, so you will never receive those messages and should remove those handlers from your code.
You are trying to draw colored text directly onto your window using TextOutA() in a WM_PAINT handler, which is fine. But per the TextOutA() documentation:
The TextOut function writes a character string at the specified location, using the currently selected font, background color, and text color.
Your WM_PAINT handler is not selecting anything into the HDC that BeginPaint() returns, before trying to draw on it. It simply needs to configure the desired font/color values as desired, eg:
HFONT hFont;
LRESULT CALLBACK WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam){
switch(uMsg){
...
case WM_CREATE:{
hFont = CreateFont(...); // or CreateFontIndirect()
break;
}
case WM_DESTROY:{
DeleteObject(hFont);
PostQuitMessage(0);
break;
}
case WM_SETTINGCHANGE:
case WM_FONTCHANGE:{
DeleteObject(hFont);
hFont = CreateFont(...); // or CreateFontIndirect()
InvalidateRect(hwnd, NULL, TRUE);
break;
}
case WM_PAINT:{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
HFONT hOldFont = (HFONT) SelectObject(hdc, hFont);
SetTextColor(hdc, ...);
SetBkColor(hdc, ...);
int iY = 7;
const char *cpaText [iY] = {
"Hello Peoples",
"",
"This is my first attempt to program using the Win32 API.",
"I can only hope it gets better with time.",
"",
"Created by \"The\" Cosmic Cruizer"
};
for (int iLoopCounter = 0; cpaText [iLoopCounter] != 0; iLoopCounter++, iY += 20) {
TextOutA (hdc, 5, iY, cpaText [iLoopCounter], strlen (cpaText [iLoopCounter]));
}
SelectObject(hdc, hOldFont);
EndPaint(hwnd, &ps);
return 0;
}
...
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}

Win32: Why is full-screen mode buggy?

Currently, I'm trying to make a simple Win32 application that switches back and forth between fullscreen and windowed mode. I'm using the Chromium way of doing this as a reference. I created a class to handle windows to make things simpler.
I expected this to work by toggling fullscreen when the F4 key was pressed. Unfortunately, the styles appear to be applied correctly, but the window doesn't resize or move to the correct area. It also snaps to the top left corner of the screen for a moment before it returns to its original position. For some reason, input for the window passes to the one below it when I toggle fullscreen. Then I have to go to Task Manager to kill the program because I can't close the window or application.
I've tried storing the styles of the HWND in a class variable at creation (it starts out in windowed mode) and using the value to create the necessary style for the fullscreen window and restoring the windowed mode window. I have also tried immediately getting the window styles with GetWindowLongPtr when the ToggleFullscreen function is called. Both of these do not work.
Here is my code:
WindowHandler.h
#include <Windows.h> // Win32 API
#ifndef WINDOWHANDLER
#define WINDOWHANDLER
class WindowHandler // WindowHandler
{
public:
WindowHandler(); // Constructor
void Destroy() { DestroyWindow(hwnd); } // Destroy the handler
void ToggleFullscreen(); // Toggle fullscreen
protected:
static LRESULT CALLBACK WindowProc // Window procedure
(
HWND hwnd,
UINT message,
WPARAM wParam,
LPARAM lParam
);
HWND hwnd; // The window
// Everything involved in fullscreen
bool fullscreen = false; // Whether the window is fullscreen or not
RECT windowRect = {}; // The restored window size
long int windowStyles = 0; // The restored window styles
long int extendedWindowStyles = 0; // The restored window extended styles
};
#endif
WindowHandler.cpp
#include "WindowHandler.h" // Header file
WindowHandler::WindowHandler() // Constructor
{
WNDCLASS wndClass = {}; // The window information
wndClass.lpfnWndProc = WindowProc;
wndClass.hInstance = GetModuleHandle(nullptr);
wndClass.lpszClassName = L"FullscreenTest";
RegisterClass(&wndClass); // Register the window
hwnd = CreateWindowEx // Create the window and store a pointer to the handler for the procedure to use
(
0,
L"FullscreenTest",
L"Stack Overflow Repro",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
nullptr,
nullptr,
GetModuleHandle(nullptr),
this
);
if (hwnd == nullptr) Destroy(); // Destroy the handler if the window is invalid
else // Otherwise...
{
GetWindowRect(hwnd, &windowRect); // Store the window size
windowStyles = GetWindowLongPtr(hwnd, GWL_STYLE); // Store the window styles
extendedWindowStyles = GetWindowLongPtr(hwnd, GWL_EXSTYLE); // Store the extended window styles
ShowWindow(hwnd, SW_SHOW); // Show the window
}
}
void WindowHandler::ToggleFullscreen() // Toggle fullscreen
{
if (!fullscreen) // If fullscreen is not enabled
{
MONITORINFO monitorInfo; // Get the monitor info
monitorInfo.cbSize = sizeof(monitorInfo);
GetMonitorInfo(MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST), &monitorInfo);
SetWindowLongPtr(hwnd, GWL_STYLE, windowStyles & ~(WS_CAPTION | WS_THICKFRAME)); // Set the window styles
SetWindowLongPtr // Set the extended window styles
(
hwnd,
GWL_EXSTYLE,
extendedWindowStyles & ~(WS_EX_DLGMODALFRAME | WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE | WS_EX_STATICEDGE)
);
SetWindowPos // Resize, move, and refresh the window
(
hwnd,
nullptr,
monitorInfo.rcMonitor.left,
monitorInfo.rcMonitor.top,
monitorInfo.rcMonitor.right - monitorInfo.rcMonitor.left,
monitorInfo.rcMonitor.bottom - monitorInfo.rcMonitor.top,
SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED
);
fullscreen = true; // Indicate that fullscreen is on
}
else // Otherwise...
{
SetWindowLongPtr(hwnd, GWL_STYLE, windowStyles); // Set the window styles
SetWindowLongPtr(hwnd, GWL_EXSTYLE, extendedWindowStyles); // Set the extended window styles
SetWindowPos // Resize, move, and refresh the window
(
hwnd,
nullptr,
windowRect.left,
windowRect.top,
windowRect.right - windowRect.left,
windowRect.bottom - windowRect.top,
SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED
);
fullscreen = false; // Indicate that fullscreen is off
}
}
LRESULT CALLBACK WindowHandler::WindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) // Window procedure
{
WindowHandler* handlerPtr; // Pointer to the window handler
if (message == WM_CREATE) // If the window is being created...
{
CREATESTRUCT* createStruct = reinterpret_cast<CREATESTRUCT*>(lParam); // Get the pointer's container
handlerPtr = reinterpret_cast<WindowHandler*>(createStruct->lpCreateParams); // Get the pointer
SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)handlerPtr); // Store the pointer
}
else handlerPtr = reinterpret_cast<WindowHandler*>(GetWindowLongPtr(hwnd, GWLP_USERDATA)); // Otherwise, get the pointer
if (handlerPtr) { // If the pointer is valid...
switch (message)
{
case WM_PAINT: // Paint the window
{
PAINTSTRUCT paintStruct;
HDC hdc = BeginPaint(hwnd, &paintStruct);
FillRect(hdc, &paintStruct.rcPaint, (HBRUSH)(COLOR_WINDOW + 1));
EndPaint(hwnd, &paintStruct);
}
return 0;
case WM_DESTROY: // Destroy the window
PostQuitMessage(0);
return 0;
case WM_KEYDOWN: // Process input
switch ((int)wParam)
{
case VK_ESCAPE: // Quit if the escape key is pressed
handlerPtr->Destroy();
break;
case VK_F4: // Toggle fullscreen if F4 is pressed
handlerPtr->ToggleFullscreen();
break;
}
return 0;
default: // Do the default action if the message was not processed
return DefWindowProc(hwnd, message, wParam, lParam);
}
}
else return DefWindowProc(hwnd, message, wParam, lParam); // Do the default action if the pointer is not valid
}
main.cpp
#include "WindowHandler.h" // Window handler
int WINAPI wWinMain(HINSTANCE, HINSTANCE, PWSTR, int) // Win32 main function
{
WindowHandler repro; // Create a window handler
MSG msg = {}; // Message structure
while (GetMessage(&msg, nullptr, 0, 0)) // Message loop
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
Replace:
windowStyles = GetWindowLongPtr(hwnd, GWL_STYLE);
extendedWindowStyles = GetWindowLongPtr(hwnd, GWL_EXSTYLE);
ShowWindow(hwnd, SW_SHOW); // Show the window
With:
ShowWindow(hwnd, SW_SHOW); // Show the window
windowStyles = GetWindowLongPtr(hwnd, GWL_STYLE);
extendedWindowStyles = GetWindowLongPtr(hwnd, GWL_EXSTYLE);
The WS_VISIBLE style bit does not get set until after that first ShowWindow(SW_SHOW).

Creating custom windows border edge disapears when resize smaller

Pretty much what the title says.
Im trying to make my own border, like that of visual studio 2015.
Once i have the border working like it should i will add a child window that is the main window for my program, the border will be the parent.
Will also try and add a outer glow once i get it working.
But the problem im having right now is, When i drag my border to resize it to make it smaller, The right or bottom start to get thinner depending on how fast i drag the mouse.
Is there a better way to do this or is there a simple step i can take to fix it.
#include <windows.h>
LPTSTR className_ = TEXT("BorderWindow");
BOOL WINAPI Init(HINSTANCE hInstance, INT cmdShow);
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam);
INT WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, INT nCmdShow) {
MSG msg;
if (!Init(hInstance, nCmdShow)) {
return FALSE;
}
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (INT)msg.wParam;
}
BOOL WINAPI Init(HINSTANCE hInstance, INT cmdShow)
{
WNDCLASSEX wcex{ 0 };
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = 0;
wcex.lpfnWndProc = (WNDPROC)WndProc;
wcex.hInstance = hInstance;
wcex.hIcon = NULL;
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_HIGHLIGHT + 1);
wcex.lpszClassName = className_;
wcex.hIconSm = NULL;
if (!RegisterClassEx(&wcex)) {
return FALSE;
}
HWND hwnd_ = CreateWindow(className_, className_, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, 200, 500, nullptr, nullptr, hInstance, nullptr);
if (!hwnd_)
return FALSE;
ShowWindow(hwnd_, cmdShow);
UpdateWindow(hwnd_);
return TRUE;
}
void CreateHole(HWND hWnd)
{
HRGN WindowRgn;
HRGN HoleRgn;
//Get the window region:
RECT windowrect;
GetWindowRect(hWnd, &windowrect);
int width = windowrect.right - windowrect.left;
int height = windowrect.bottom - windowrect.top;
WindowRgn = CreateRectRgn(0, 0, width, height);
//Create the hole region:
HoleRgn = CreateRectRgn(2, 2, width - 2, height - 2);
CombineRgn(WindowRgn, WindowRgn, HoleRgn, RGN_DIFF);
SetWindowRgn(hWnd, WindowRgn, TRUE);
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam)
{
switch (message)
{
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_SIZE:
CreateHole(hwnd);
return 0;
case WM_NCCALCSIZE:
// remove default borders
return 0;
case WM_NCHITTEST:
{
RECT rc;
GetClientRect(hwnd, &rc);
POINT pt = { LOWORD(lparam), HIWORD(lparam) };
ScreenToClient(hwnd, &pt);
if (pt.y > (rc.bottom - 5))
{
if (pt.x > (rc.right - 5))
{
return HTBOTTOMRIGHT;
}
}
return HTBORDER;
}
}
return DefWindowProc(hwnd, message, wparam, lparam);
}
If you only need rectangular frame, an easier solution can be achieved as follows:
Window style should be such that normally the whole frame would be shown (WS_CAPTION|WS_POPUP works well for me).
Call DwmExtendFrameIntoClientArea() with MARGINS{0,0,0,1}.
Call SetWindowPos(nullptr, 0, 0, 0, 0, SWP_NOZORDER|SWP_NOOWNERZORDER|SWP_NOMOVE|SWP_NOSIZE|SWP_FRAMECHANGED) to recalculate NC area.
Return 0 from WM_NCCALCSIZE if wParam is TRUE. This has the effect of extending the client area to the window size including frame. The regular window frame will be removed, but shadow will still be drawn by DWM (see also remarks section of WM_NCCALCSIZE).
In WM_PAINT draw your frame and content area as you like but make sure to set opaque alpha channel for the margin defined by the DwmExtendFrameIntoClientArea() call. Otherwise part of regular frame would be visible in this area. You may use GDI+ for that as most regular GDI functions ignore alpha channel.
You can put child controls into this window, just as normal. Just make sure child controls don't overlap the margin defined by the DwmExtendFrameIntoClientArea() call because most GDI controls ignore the alpha channel.

Smooth window resizing in Windows (using Direct2D 1.1)?

It annoys me that the resizing of windows in Windows is not as "smooth" as it I'd like it to be (this is the case with Windows programs in general, not just my own. Visual Studio is a good example). It makes the OS and its programs feel "flimsy" and "cheap" (yes, I care about how programs and user interfaces feel, in the same way I care about the sound and feel of closing a car door. It's a reflection of build quality), which in my view affects the overall UX and ultimately the perception of the brand.
The redrawing of window contents simply does not keep up with mouse movement during resize. Whenever I resize a window, there is a "stuttering" / "flickering" effect, seemingly due to the previous-size-contents of the window being redrawn in the new, resized window frame before the new, resized contents are drawn.
I am building a Win32 application (x64) that uses Direct2D 1.1 to draw its UI, and given the speed of Direct2D, i think it should be unnecessary to suffer such artifacts in an OS in 2014. I am on Windows 8.1 myself, but targeting Windows 7 and up with this application.
The "previous size" effect is especially discernible when maximizing a small window (since the difference in window size is sufficiently great to easily contrast the image of the old content as it flashes briefly in the upper left corner of the larger window with the new content subsequently being painted over it).
This is what appears to be going on:
(Let's say there's a fully rendered window on screen, size 500 x 500 pixels).
I maximize the window:
The window frame is maximized
The old 500 x 500 content is drawn in the new frame, before..
..the maximized window is repainted with properly sized content.
I'm wondering if there's any way to mitigate this (i.e. get rid of step 4) - via intercepting a Windows Message, for example - and avoid the window being repainted at the new size with the old content before the final re-rendering of the new content happens. It's like Windows does the window redrawing itself, using whatever graphics it already has available, BEFORE it bothers to ask me to provide updated content with a WM_PAINT message or similar.
Can it be done?
Edit: It seems that WM_WINDOWPOSCHANGING / WM_SIZING provides "early access" to the new size data, but I still haven't managed to suppress the painting of the old content.
My WndProc looks like this:
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_ERASEBKGND:
return 1;
case WM_PAINT:
PAINTSTRUCT ps;
BeginPaint(hWnd, &ps);
D2DRender();
EndPaint(hWnd, &ps);
return 0;
case WM_SIZE:
if (DeviceContext && wParam != SIZE_MINIMIZED)
{
D2DResizeTargetBitmap();
D2DRender();
}
return 0;
case WM_DISPLAYCHANGE:
D2DRender();
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
The window does not have CS_HREDRAW or CS_VREDRAW set. The swapchain is double buffered and the Present call is made with SyncInterval = 0.
I am aware that recreating the swapchain buffers every time the window size changes does create some overhead compared to plain redrawing on a static window surface. However, the "stuttering" is not caused by that, as it happens even when buffer resizing is disabled and existing window contents are simply scaled during window resizing (although that does make it keep up better with mouse movement).
There is a way to prevent the needless BitBlt mentioned in step 4 above.
Until Windows 8 it could be done either by creating your own custom implementation of WM_NCCALCSIZE to tell Windows to blit nothing (or to blit one pixel on top of itself), or alternately you could intercept WM_WINDOWPOSCHANGING (first passing it onto DefWindowProc) and set WINDOWPOS.flags |= SWP_NOCOPYBITS, which disables the BitBlt inside the internal call to SetWindowPos() that Windows makes during window resizing. This has the same eventual effect of skipping the BitBlt.
However, nothing can be so simple. With the advent of Windows 8/10 Aero, apps now draw into an offscreen buffer which is then composited by the new, evil DWM.exe window manager. And it turns out DWM.exe will sometimes do its own BitBlt type operation on top of the one already done by the legacy XP/Vista/7 code. And stopping DWM from doing its blit is much harder; so far I have not seen any complete solutions.
So you need to get through both layers. For sample code that will break through the XP/Vista/7 layer and at least improve the performance of the 8/10 layer, see:
How to smooth ugly jitter/flicker/jumping when resizing windows, especially dragging left/top border (Win 7-10; bg, bitblt and DWM)?
What if you have a borderless childwindow (the type that only renders inside the parent) at a fixed size (same as fullscreen resolution), you should get a lot smoother results because there is no memory reallocation (which i think is what causes the jitterieness).
If it's still not perfect, look into both WM_SIZE and WM_SIZING and check if you can do some magic with them. For instance, on WM_SIZING you could return true telling Windows you handled the message (leaving the window as is) and you re-render your UI to a buffer with the size provided by WM_SIZING and when that is done, you send your own WM_SIZING but with a manipulated unused bit in WPARAM (along with its previous content) that tells you you have a pre-rendered buffer for this that you can just blit out. From the WM_SIZING documentation on msdn it looks like WPARAM should have a couple of bits at your disposal.
Hope this helps.
When calling CreateSwapChainForHwnd, ensure that you have set the swap chain description Scaling property to DXGI_SCALING_NONE. This is only supported on Windows 7 with the Platform Update, so you may need to fall back to the default DXGI_SCALING_STRETCH (the latter is what is causing the flickering).
Set WM_SETREDRAW to FALSE, do your resizing, then reenable drawing, invalidate the window and the OS will blit it.
I've done this for button enabling and disabling buttons when selecting different items from a list, never for an entire window.
This is the best I've come up with and resizes great although the backbuffer blitting causes some edge flickering, haven't tested with DX or OGL yet but it should work even better with hardware acceleration. It's a bit bulky but will do as a proof of concept.
If the canvas could be clipped without using MDI that would be even better, like using a bitmask buffer.
One thing i'm not happy about is the position coords of the child window because they might not work on all systems, but a combination of GetSystemMetrics calls to get border and caption sizes should fix that.
/* Smooth resizing of GDI+ MDI window
*
* Click window to resize, hit Escape or Alt+F4 to quit
*
* Character type is set to multibyte
* Project->Properties->Config Properties->General->Character Set = Multibyte
*
* Pritam 2014 */
// Includes
#include <Windows.h>
#include <gdiplus.h>
#pragma comment (lib,"Gdiplus.lib")
using namespace Gdiplus;
// Max resolution
#define XRES 1600
#define YRES 900
// Globals
bool resizing = false;
HWND parent, child; // child is the canvas window, parent provides clipping of child
Bitmap * buffer;
// Render
void Render() {
// Get parent client size
RECT rc;
GetClientRect(parent, &rc);
// Draw backbuffer
Graphics * g = Graphics::FromImage(buffer);
// Clear buffer
g->Clear(Color(100, 100, 100));
// Gray border
Pen pen(Color(255, 180, 180, 180));
g->DrawRectangle(&pen, 10, 10, rc.right - 20, rc.bottom - 20);
pen.SetColor(Color(255, 0, 0, 0));
g->DrawRectangle(&pen, 0, 0, rc.right - 1, rc.bottom - 1);
// Draw buffer to screen
PAINTSTRUCT ps;
HDC hdc = BeginPaint(child, &ps);
Graphics graphics(hdc);
graphics.DrawImage(buffer, Point(0, 0));
// Free
EndPaint(child, &ps);
}
// MDI Callback
LRESULT CALLBACK MDICallback(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) {
switch(message) {
case WM_LBUTTONDOWN:
resizing = true; // Start resizing
return 0;
break;
case WM_KEYDOWN:
if(wparam == VK_ESCAPE) { // Exit on escape
PostQuitMessage(0);
}
TranslateMessage((const MSG *)&message);
return 0;
break;
case WM_PAINT:
Render();
return 0;
break;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
break;
}
return DefMDIChildProc(hwnd, message, wparam, lparam);
}
// Parent window callback
LRESULT CALLBACK WndCallback(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) {
return DefFrameProc(hwnd, child, message, wparam, lparam);
}
// Create windows
bool CreateWindows(void) {
// Parent class
WNDCLASSEX wndclass;
ZeroMemory(&wndclass, sizeof(wndclass)); wndclass.cbSize = sizeof(wndclass);
wndclass.style = CS_NOCLOSE;
wndclass.lpfnWndProc = WndCallback;
wndclass.hInstance = GetModuleHandle(NULL);
wndclass.lpszClassName = "WNDCALLBACKPARENT";
wndclass.hIcon = LoadIcon(NULL, IDI_WINLOGO);
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
if(!RegisterClassEx(&wndclass)) return false;
// MDI class
wndclass.style = CS_OWNDC | CS_VREDRAW | CS_HREDRAW;
wndclass.lpfnWndProc = MDICallback;
wndclass.lpszClassName = "MDICALLBACKCANVAS";
if(!RegisterClassEx(&wndclass)) return false;
// Parent window styles
DWORD style = WS_POPUP | WS_CLIPCHILDREN;
DWORD exstyle = 0;
// Set initial window size and position
RECT rc;
rc.right = 640;
rc.bottom = 480;
AdjustWindowRectEx(&rc, style, false, exstyle);
rc.left = 20;
rc.top = 20;
// Create window
if(!(parent = CreateWindowEx(exstyle, "MDICLIENT", "MDI Resize", style, rc.left, rc.top, rc.right, rc.bottom, NULL, NULL, wndclass.hInstance, NULL))) return false;
// MDI window styles
style = MDIS_ALLCHILDSTYLES;
exstyle = WS_EX_MDICHILD;
// Set MDI size
rc.left = - 8; // The sizes occupied by borders and caption, if position is not correctly set an ugly caption will appear
rc.top = - 30;
rc.right = XRES;
rc.bottom = YRES;
AdjustWindowRectEx(&rc, style, false, exstyle);
// Create MDI child window
if(!(child = CreateWindowEx(exstyle, "MDICALLBACKCANVAS", "", style, rc.left, rc.top, rc.right, rc.bottom, parent, NULL, wndclass.hInstance, NULL))) return 8;
// Finalize
ShowWindow(child, SW_SHOW);
ShowWindow(parent, SW_SHOWNORMAL);
// Success
return true;
}
// Resize
void Resize(void) {
// Init
RECT rc, rcmdi;
GetClientRect(child, &rcmdi); // Use mdi window size to set max resize for parent
GetWindowRect(parent, &rc);
// Get mouse position
POINT mp;
GetCursorPos(&mp);
// Set new size
rc.right = mp.x - rc.left + 10;
rc.bottom = mp.y - rc.top + 10;
// Apply min & max size
if(rc.right < 240) rc.right = 240; if(rc.bottom < 180) rc.bottom = 180;
if(rc.right > rcmdi.right) rc.right = rcmdi.right; if(rc.bottom > rcmdi.bottom) rc.bottom = rcmdi.bottom;
// Update window size
SetWindowPos(parent, NULL, rc.left, rc.top, rc.right, rc.bottom, SWP_NOZORDER | SWP_NOMOVE);
// Make sure client is entirely repainted
GetClientRect(child, &rc);
InvalidateRect(child, &rc, false);
UpdateWindow(child);
// Stop resizing if mousebutton is up
if(!(GetKeyState(VK_LBUTTON) & 1 << (sizeof(short) * 8 - 1)))
resizing = false;
}
// Main
int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE pinstance, LPSTR cmdline, int cmdshow) {
// Initiate GDI+
ULONG_PTR gdiplusToken;
GdiplusStartupInput gdiplusStartupInput;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
buffer = new Bitmap(XRES, YRES, PixelFormat24bppRGB);
// Create windows
if(!CreateWindows()) return 1;
// Main loop
bool running = true;
MSG message;
while(running) {
// Check message or pass them on to window callback
if(PeekMessage(&message, NULL, 0, 0, PM_REMOVE)) {
if(message.message == WM_QUIT) {
running = false;
} else {
if(!TranslateMDISysAccel(child, &message)) {
TranslateMessage(&message);
DispatchMessage(&message);
}
}
}
// Resize
if(resizing)
Resize();
// Sleep a millisecond to spare the CPU
Sleep(1);
}
// Free memmory and exit
delete buffer;
GdiplusShutdown(gdiplusToken);
return 0;
}
Edit: Another example using "bitmask"/layered window.
// Escape to quit, left mousebutton to move window, right mousebutton to resize.
// And again char set must be multibyte
// Include
#include <Windows.h>
#include <gdiplus.h>
#pragma comment (lib,"Gdiplus.lib")
using namespace Gdiplus;
// Globals
Bitmap * backbuffer;
int xres, yres;
bool move, size;
POINT framePos, frameSize, mouseOffset;
// Renders the backbuffer
void Render(void) {
if(!backbuffer) return;
// Clear window with mask color
Graphics * gfx = Graphics::FromImage(backbuffer);
gfx->Clear(Color(255, 0, 255));
// Draw stuff
SolidBrush brush(Color(120, 120, 120));
gfx->FillRectangle(&brush, framePos.x, framePos.y, frameSize.x, frameSize.y);
}
// Paints the backbuffer to window
void Paint(HWND hwnd) {
if(!hwnd) return;
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
Graphics gfx(hdc);
gfx.DrawImage(backbuffer, Point(0, 0));
EndPaint(hwnd, &ps);
}
void HandleMove(HWND hwnd) {
// Get mouse position
POINT mouse;
GetCursorPos(&mouse);
// Update frame position
framePos.x = mouse.x - mouseOffset.x;
framePos.y = mouse.y - mouseOffset.y;
// Redraw buffer and invalidate & update window
Render();
InvalidateRect(hwnd, NULL, false);
UpdateWindow(hwnd);
// Stop move
if(!(GetKeyState(VK_LBUTTON) & 1 << (sizeof(short) * 8 - 1)))
move = false;
}
void HandleSize(HWND hwnd) {
// Get mouse position
POINT mouse;
GetCursorPos(&mouse);
// Update frame size
frameSize.x = mouse.x + mouseOffset.x - framePos.x;
frameSize.y = mouse.y + mouseOffset.y - framePos.y;
//frameSize.x = mouse.x + mouseOffset.x;
//frameSize.y = mouse.y + mouseOffset.y;
// Redraw buffer and invalidate & update window
Render();
InvalidateRect(hwnd, NULL, false);
UpdateWindow(hwnd);
// Stop size
if(!(GetKeyState(VK_RBUTTON) & 1 << (sizeof(short) * 8 - 1)))
size = false;
}
LRESULT CALLBACK WindowCallback(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) {
POINTS p;
switch(msg) {
case WM_KEYDOWN:
if(wparam == VK_ESCAPE) PostQuitMessage(0);
return 0;
break;
case WM_LBUTTONDOWN:
p = MAKEPOINTS(lparam); // Get mouse coords
mouseOffset.x = p.x - framePos.x;
mouseOffset.y = p.y - framePos.y;
move = true;
break;
case WM_RBUTTONDOWN:
p = MAKEPOINTS(lparam);
mouseOffset.x = framePos.x + frameSize.x - p.x;
mouseOffset.y = framePos.y + frameSize.y - p.y;
size = true;
break;
case WM_PAINT:
Paint(hwnd);
return 0;
break;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
break;
}
return DefWindowProc(hwnd, msg, wparam, lparam);
}
// Main
int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE pinstance, LPSTR cmdline, int cmdshow) {
// Init resolution, frame
xres = GetSystemMetrics(SM_CXSCREEN);
yres = GetSystemMetrics(SM_CYSCREEN);
move = false; size = false;
framePos.x = 100; framePos.y = 80;
frameSize.x = 320; frameSize.y = 240;
mouseOffset.x = 0; mouseOffset.y = 0;
// Initiate GDI+
ULONG_PTR gdiplusToken;
GdiplusStartupInput gdiplusStartupInput;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
// Init backbuffer
backbuffer = ::new Bitmap(xres, yres, PixelFormat24bppRGB);
Render();
// Window class
WNDCLASSEX wc; ZeroMemory(&wc, sizeof(wc)); wc.cbSize = sizeof(wc);
wc.style = CS_OWNDC | CS_VREDRAW | CS_HREDRAW;
wc.lpfnWndProc = WindowCallback;
wc.hInstance = GetModuleHandle(NULL);
wc.lpszClassName = "SingleResizeCLASS";
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
if(!RegisterClassEx(&wc)) return 1;
// Create window
HWND hwnd;
DWORD style = WS_POPUP;
DWORD exstyle = WS_EX_LAYERED;
if(!(hwnd = CreateWindowEx(exstyle, wc.lpszClassName, "Resize", style, 0, 0, xres, yres, NULL, NULL, wc.hInstance, NULL)))
return 2;
// Make window fully transparent to avoid the display of unpainted window
SetLayeredWindowAttributes(hwnd, 0, 0, LWA_ALPHA);
// Finalize
ShowWindow(hwnd, SW_SHOWNORMAL);
UpdateWindow(hwnd);
// Make window fully opaque, and set color mask key
SetLayeredWindowAttributes(hwnd, RGB(255, 0, 255), 0, LWA_COLORKEY);
// Main loop
MSG msg;
bool running = true;
while(running) {
// Check message
if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
if(msg.message == WM_QUIT) {
running = false;
} else {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
// Move or size frame
if(move) { HandleMove(hwnd); }
if(size) { HandleSize(hwnd); }
Sleep(1);
}
// Free memory
::delete backbuffer;
backbuffer = NULL;
GdiplusShutdown(gdiplusToken);
// Exit
return 0;
}
While your aim is laudable, I suspect that any attempt to do this will just end up as a fight between you and Windows - which you will not win (though you might manage to fight your way to an honourable draw). Sorry to be negative.

Win32 C++ SetLayeredWindowAttributes is either fully opaque or fully transparent; nothing in between

So I have a 2nd Window created within my program like:
#define WINDOW_CLASS_NAME "WINCLASSFULL"
WNDCLASSEX winclass;
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_CLOSE:
DestroyWindow(hwnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
some function {
HINSTANCE hInstance = (HINSTANCE)GetModuleHandle(NULL);
// first fill in the window class stucture
winclass.cbSize = sizeof(WNDCLASSEX);
winclass.style = CS_DBLCLKS | CS_OWNDC |
CS_HREDRAW | CS_VREDRAW;
winclass.lpfnWndProc =WndProc;
winclass.cbClsExtra = 0; //reserve data space
winclass.cbWndExtra = 0; //
winclass.hInstance = hInstance; //set instance of application
winclass.hIcon = NULL;
winclass.hCursor = LoadCursor(NULL, IDC_ARROW); //load cursor type
winclass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); //set background brush
winclass.lpszMenuName = NULL;
winclass.lpszClassName = WINDOW_CLASS_NAME; //set Windows class name
winclass.hIconSm = NULL;
hWnd= CreateWindowEx(WS_EX_LAYERED, // extended style
WINDOW_CLASS_NAME, // class
"Demo", // title
WS_POPUP,
x,y,
width,height,
NULL,
NULL,
hInstance,// instance of this application
NULL))) // extra creation parms
}
Now my issue is if I apply
Where 255 can be anything between 1-255
SetLayeredWindowAttributes(hWnd,RGB(0,0,0),255,LWA_COLORKEY|LWA_ALPHA)
The window is fully opaque i can't see anything behind it
This is fully transparent:
SetLayeredWindowAttributes(hWnd,RGB(0,0,0),0,LWA_COLORKEY|LWA_ALPHA)
How can I get
SetLayeredWindowAttributes(hWnd,RGB(0,0,0),128,LWA_COLORKEY|LWA_ALPHA)
To work - i.e. so I can partially see my window on top; and partially see window behind it. I've checked the doco on MSDN here but I'm obviously missing something Refer Microsoft Library
Try to specify only LWA_ALPHA, not both LWA_COLORKEY and LWA_ALPHA