Is there a graceful way to handle toggling between fullscreen and windowed mode in a Windows OpenGL application? - c++

I'm wondering if it's possible to toggle back and forth between fullscreen mode and windowed mode in an OpenGL window(I'm writing for Windows using C++ and win32), without destroying the OpenGL context, and thus having to reload assets(Textures, VBOs, etc) in the process?
This is undesirable because it introduces a delay in switching between fullscreen and windowed mode, potentially a long one, as well as making it easier to screw things up by forgetting to reinitialize something.
As a followup to that, are there certain visual effects that are broken by managing to do this?
I've done a fair bit of searching and reading for the past few days, and despite a lot of flaming of SDL and other frameworks for having the same problem(I'm not using them anyway, but...), the best I've managed to find is a possible lead on opening a 1x1 window in the background to retain the context while a secondary window is destroyed or created at whim. And that's seeming unreliable from the comments I found regarding it, and seems very kludgey regardless.
Is there a proper way to do this, or is the proper way the often-given-as-an-example method of destroying your window, and recreating it, including destroying your OpenGL context and recreating it?

Basically it's just resizing the window and specifying flags that the border is invisible.
SetWindowLongPtr(hWnd, GWL_STYLE,
WS_SYSMENU | WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE);
MoveWindow(hWnd, 0, 0, width, height, TRUE);
to set it back:
RECT rect;
rect.left = 0;
rect.top = 0;
rect.right = width;
rect.bottom = height;
SetWindowLongPtr(hWnd, GWL_STYLE, WS_OVERLAPPEDWINDOW | WS_VISIBLE);
AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, FALSE);
MoveWindow(hWnd, 0, 0, rect.right-rect.left, rect.bottom-rect.top, TRUE);
or for a not-resizable window:
SetWindowLongPtr(hWnd, GWL_STYLE, WS_CAPTION | WS_POPUPWINDOW | WS_VISIBLE);
AdjustWindowRect(&rect, WS_CAPTION | WS_POPUPWINDOW, FALSE);
MoveWindow(hWnd, 0, 0, rect.right-rect.left, rect.bottom-rect.top, TRUE);
and then just resize your OpenGL viewport settings.
If you want to set the display mode too, use this:
// change display mode if destination mode is fullscreen
if (fullscreen) {
DEVMODE dm;
dm.dmSize = sizeof(DEVMODE);
dm.dmPelsWidth = width;
dm.dmPelsHeight = height;
dm.dmBitsPerPel = bitsPerPixel;
dm.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL;
success = ChangeDisplaySettings(&dm, 0) == DISP_CHANGE_SUCCESSFUL;
}
// reset display mode if destination mode is windowed
if (!fullscreen)
success = ChangeDisplaySettings(0, 0) == DISP_CHANGE_SUCCESSFUL;

Here's the code I use, which uses SetWindowPos() rather than MoveWindow(), as discussed in the comments of the other answer.
void enter_fullscreen(application* App)
{
POINT Point = {0};
HMONITOR Monitor = MonitorFromPoint(Point, MONITOR_DEFAULTTONEAREST);
MONITORINFO MonitorInfo = { sizeof(MonitorInfo) };
if (GetMonitorInfo(Monitor, &MonitorInfo)) {
DWORD Style = WS_POPUP | WS_VISIBLE;
SetWindowLongPtr(App->Window, GWL_STYLE, Style);
SetWindowPos(App->Window, 0, MonitorInfo.rcMonitor.left, MonitorInfo.rcMonitor.top,
MonitorInfo.rcMonitor.right - MonitorInfo.rcMonitor.left, MonitorInfo.rcMonitor.bottom - MonitorInfo.rcMonitor.top,
SWP_FRAMECHANGED | SWP_SHOWWINDOW);
}
App->IsFullscreen = true;
}
void exit_fullscreen(application* App)
{
bool WasMaximized = App->IsMaximized;
DWORD Style = WS_OVERLAPPEDWINDOW | WS_VISIBLE | WS_CLIPCHILDREN;
if (WasMaximized) {
Style = Style | WS_MAXIMIZE;
}
ivec2 WindowPosition = WasMaximized ? App->WindowPosition : App->NormalWindowPosition;
ivec2 WindowSize = WasMaximized ? App->WindowSize : App->NormalWindowSize;
SetWindowLongPtr(App->Window, GWL_STYLE, Style);
SetWindowPos(App->Window, 0,
WindowPosition.X, WindowPosition.Y, WindowSize.X, WindowSize.Y,
SWP_FRAMECHANGED | SWP_SHOWWINDOW);
App->IsFullscreen = false;
}
I call it on F11, but also on WM_ACTIVATE. Otherwise the window would sometimes keep rendering on top on Windows 7, even if another application would receive all messages, including mouse and keyboard.

Related

How to create a window that behaves like taskbar?

I want to ask how to create a window that behaves like taskbar (shell_traywnd)?
In a windows app called Enable Viacam (camera mouse for disabled people) I saw that the app creates a taskbar-like window on the top of the screen (see the image below) which pulls all other windows underneath it.
Enable_Viacam's window (top of screen)
I used Winspector software to examine this Enable Viacam's window to see its WS_/WS_EX_ properties so that I would try emulate it, but calling CreateWindowEx with those properties didn't give me the wanted result..
Here's my attempt (message loop & window procedure not shown here)
hwnd = CreateWindowEx(
WS_EX_TOOLWINDOW | WS_EX_TOPMOST | WS_EX_LEFT | WS_EX_LTRREADING | WS_EX_RIGHTSCROLLBAR | WS_EX_CONTROLPARENT,
"#32770","Window",
WS_OVERLAPPEDWINDOW | WS_POPUP | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_BORDER | DS_3DLOOK,
0, /* x */
0, /* y */
GetSystemMetrics(SM_CXSCREEN), /* width */
50, /* height */
NULL,NULL,hInstance,NULL);
Any ideas greatly appreciated,
thank you!
Apparently this window type is called an appbar
I created window with style WS_EX_TOOLWINDOW and WS_POPUP and followed that MSDN link
My code now is
APPBARDATA abd = {0};
abd.cbSize = sizeof(APPBARDATA);
abd.hWnd = hwnd;
abd.uCallbackMessage = 888;
SHAppBarMessage(ABM_NEW, &abd);
abd.uEdge = ABE_TOP;
abd.rc.left = 0;
abd.rc.right = GetSystemMetrics(SM_CXSCREEN);
abd.rc.top = 0;
abd.rc.bottom = height;
SHAppBarMessage(ABM_QUERYPOS, &abd);
abd.rc.bottom = abd.rc.top + height;
SHAppBarMessage(ABM_SETPOS, &abd);
Have fun coding guys

How change resolution and update window without flickering

I need to change the resolution different times and keep update the windows.
Actually I use this code:
bool SetDiplayResolution(int Width, int Height, int Refresh = 0)
{
LONG Outout;
DEVMODE desiredMode;
memset(&desiredMode, 0, sizeof(desiredMode));
desiredMode.dmSize = sizeof(desiredMode);
if (EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &desiredMode) != 0)
{
desiredMode.dmSize = sizeof(DEVMODE);
desiredMode.dmPelsWidth = Width;
desiredMode.dmPelsHeight = Height;
if (Refresh > 0)
{
desiredMode.dmDisplayFrequency = Refresh;
desiredMode.dmFields = DM_PELSHEIGHT | DM_PELSWIDTH | DM_DISPLAYFREQUENCY;
}
else
{
desiredMode.dmFields = DM_PELSHEIGHT | DM_PELSWIDTH;
}
Outout = ChangeDisplaySettings(&desiredMode, 0);
}
return Outout;
}
void myfunction
{
HWND hWnd = GetActiveWindow();
SetDiplayResolution(1920, 1080);
SetWindowPos(hWnd, 0, 0, 0, 1920, 1080, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
UpdateWindow(hWnd);
}
This code work fine but unfortunatenly the transaction beetween the old and new resolution produce some very short, but visble annoyng effects:
Temporary presence of the windows bar.
The screen flash for one instant.
I don't known if exist a way to solve. I have seen in some forum that other create a secondary top most window in order to avoid these side effects and then destroy this secondary window.
I don't sure if this is a good way.
Unfortunatenly I don't have access to window events becouse my is a dll (I have not create the window, but I have the handle).
Can you please help me ?
Thanks !

Set a window transparent

I have been trying to set BlueStacks window transparent:
DWORD MakeWindowTransparent(HWND hWnd, unsigned char factor)
{
/* First, see if we can get the API call we need. If we've tried
* once, we don't need to try again. */
if (!initialized)
{
HMODULE hDLL = LoadLibrary(L"user32");
pSetLayeredWindowAttributes =
(PSLWA)GetProcAddress(hDLL, "SetLayeredWindowAttributes");
initialized = TRUE;
}
if (pSetLayeredWindowAttributes == NULL)
return FALSE;
/* Windows need to be layered to be made transparent. This is done
* by modifying the extended style bits to contain WS_EX_LAYARED. */
SetLastError(0);
auto winlong = SetWindowLong(hWnd,
GWL_EXSTYLE,
GetWindowLong(hWnd, GWL_EXSTYLE) | WS_EX_LAYERED);
if ((winlong == 0) && (GetLastError() != 0)) {
auto error = GetLastErrorAsString();
return FALSE;
}
if (!pSetLayeredWindowAttributes(hWnd,RGB(255, 255, 255),factor, LWA_COLORKEY | LWA_ALPHA))
{
auto error = GetLastErrorAsString();
return FALSE;
}
return TRUE;
}
int main() {
HWND hWnd = FindWindowA(NULL, L"BlueStacks");
MakeWindowTransparent(hWnd, 0);
}
BlueStacks can run in opengl and directx, I have tested the code above, using both modes.
MakeWindowTransparent is returning 0
pSetLayeredWindowAttributes auto error = GetLastErrorAsString(); error returned is: wrong parameter.
I have tested the code with other OpenGL windows, and it did not pause in any of the errors, also the window got transparent correctly.
Some information I have collected about the window:
Appreciate any help.
Why are you using both flags LWA_COLORKEY | LWA_ALPHA? If you are specifying a color RGB(255, 255, 255), just use LWA_COLORKEY.
Also, why are you messing with GetProcAddress? SetLayeredWindowAttributes is available starting with Windows 2000; are you targeting platforms older than that?
I am not familiar with BlueStacks, but SetLayeredWindowAttributes to make a window transparent is only working part of the time suggests that SetLayeredWindowAttributes doesn't work with Direct3D; do you know if BlueStacks uses Direct3D?
For OpenGL see this: How to make an OpenGL rendering context with transparent background?
UPDATE
I was playing with that BlueStacks, and figured that you can re-parent it to another window (that's not recommended, as you will need to handle some edge cases). Anyway, I used an existing Notepad window and was able to set alpha on it, and that affected the child BlueStacks window:
int main() {
HWND hWnd = FindWindow(NULL, L"BlueStacks");
HWND hWndN = FindWindow(NULL, L"Untitled - Notepad");
::SetParent(hWnd, hWndN);
auto winlong1 = SetWindowLongPtr(hWnd, GWL_EXSTYLE, 0);
auto winlong2 = SetWindowLongPtr(hWnd, GWL_STYLE, WS_CHILD | WS_VISIBLE);
::SetWindowPos(hWnd, 0, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOSIZE | SWP_NOZORDER | SWP_NOREDRAW | SWP_NOACTIVATE);
MakeWindowTransparent(hWndN, 200);
}
I've also cleaned up your function to get rid of GetProcAddress:
DWORD MakeWindowTransparent(HWND hWnd, unsigned char factor)
{
auto winlong = SetWindowLong(hWnd,
GWL_EXSTYLE,
GetWindowLong(hWnd, GWL_EXSTYLE) | WS_EX_LAYERED);
if ((winlong == 0) && (GetLastError() != 0)) {
return FALSE;
}
if (!SetLayeredWindowAttributes(hWnd, 0, factor, LWA_ALPHA))
{
return FALSE;
}
return TRUE;
}

Clearing the screen after switching away from fullscreen mode?

So I've got an OpenGL application running that can toggle between fullscreen mode and windowed mode. It currently does this by resizing the window and changing styles.
However, it seems to not invalidate the screen when switching from fullscreen mode to windowed mode, which leaves things I've drawn lingering onscreen after the switch.
Interestingly, it only exhibits this behavior in single monitor mode. If I'm running with multiple monitors, it invalidates okay, and clears my drawing.
I don't think this is a driver bug, as it's happening on two separate computers using two separate video cards(although admittedly they are both nVidia.), I'm thinking I'm doing something wrong somewhere.
I've tried a bunch of methods for getting Windows to clear the screen of my previously fullscreen drawings, but nothing seems to work. InvalidateRect(), RedrawWindow(), ChangeDisplaySettings()...
Specifically:
InvalidateRect(m_hwnd, &rectx, true); // rect being the dimensions of either the screen or my window.
InvalidateRect(HWND_DESKTOP, NULL, TRUE); // Doesn't seem to do anything.
RedrawWindow(NULL, NULL, NULL, RDW_INVALIDATE | RDW_ALLCHILDREN | RDW_UPDATENOW);
ChangeDisplaySettings(NULL, 0);
Well, actually, one thing that does seem to work is ShowWindow(hwnd, SW_HIDE) before resizing. However that loses focus for a moment, allowing other applications to grab my application's input, and seems a bad way to go about it.
I should note that I'm not doing any actual display mode changes when I'm seeing this behavior; just staying at the current resolution for fullscreen.
I'm a bit clueless where I'm going wrong. Simplified code:
if(m_isFullscreen)
{
ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN);
}
else
{
ChangeDisplaySettings(&m_dmSavedScreenSettings, 0);
}
if(m_isFullscreen)
{
dwExStyle = WS_EX_APPWINDOW;
dwStyle = WS_POPUP;
ShowCursor(false);
}
else
{
dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
dwStyle = WS_OVERLAPPEDWINDOW;
if(m_isRunning) // Because ShowCursor uses a counter to indicate, and windowed mode defaults to cursor on, we don't need to increment the counter and double it being on.
{
ShowCursor(true);
}
}
RECT rect;
rect.left = 0;
rect.top = 0;
if(m_isFullscreen) { rect.right = 1280; } else { rect.right = 640; }
if(m_isFullscreen) { rect.bottom = 1024; } else { rect.bottom = 480; }
AdjustWindowRectEx(&rect, dwStyle, false, dwExStyle);
SetWindowLongPtr(m_hwnd, GWL_STYLE, dwStyle | WS_CLIPCHILDREN | WS_CLIPSIBLINGS);
SetWindowLongPtr(m_hwnd, GWL_EXSTYLE, dwExStyle);
if(m_isFullscreen)
{
MoveWindow(m_hwnd, 0, 0, 1280, 1024, true);
}
else
{
MoveWindow(m_hwnd, 0, 0, 640, 480, true); // windowed
}
And that's more or less it. Some other supporting code and error checking, but that's what I'm doing... dmSavedSettings is saved before m_hwnd is assigned from NULL, and not afterwards. My initial window creation works fine, and fullscreen works fine. It's just returning to Windowed after being fullscreen that's the issue.
If you set a null background brush in your window class, windows will not be cleared automatically. You must add a WM_PAINT handler that calls your OpenGL display handler, which in turn clears the viewport (glClearColor) and redraws.
As datenwolf mentions in another answer's comment, you want to use SetWindowPos() instead of MoveWindow() when making use of SetWindowLongPtr().
My dirty background problems were solved by calling ChangeDisplaySettings(NULL, 0) AFTER resizing my window. Doing it before does little, but afterwards appears to work fine.

Disable Window Resizing Win32

how do I disable resizing by dragging the edge of windows?
Here is my window creation code
bool CreateGLWindow(char* title, int width, int height)
{
GLuint PixelFormat; // Holds The Results After Searching For A Match
WNDCLASS wc; // Windows Class Structure
DWORD dwExStyle; // Window Extended Style
DWORD dwStyle; // Window Style
RECT WindowRect; // Grabs Rectangle Upper Left / Lower Right Values
WindowRect.left=(long)0; // Set Left Value To 0
WindowRect.right=(long)width; // Set Right Value To Requested Width
WindowRect.top=(long)0; // Set Top Value To 0
WindowRect.bottom=(long)height; // Set Bottom Value To Requested Height
hInstance = GetModuleHandle(NULL); // Grab An Instance For Our Window
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Redraw On Size, And Own DC For Window.
wc.lpfnWndProc = (WNDPROC) WndProc; // WndProc Handles Messages
wc.cbClsExtra = 0; // No Extra Window Data
wc.cbWndExtra = 0; // No Extra Window Data
wc.hInstance = hInstance; // Set The Instance
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // Load The Default Icon
wc.hCursor = LoadCursor(NULL, IDC_ARROW); // Load The Arrow Pointer
wc.hbrBackground = NULL; // No Background Required For GL
wc.lpszMenuName = NULL; // We Don't Want A Menu
wc.lpszClassName = "OpenGL"; // Set The Class Name
if (!RegisterClass(&wc)) // Attempt To Register The Window Class
{
MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return false; // Return FALSE
}
dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Window Extended Style
dwStyle=WS_OVERLAPPEDWINDOW; // Windows Style
AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle); // Adjust Window To True Requested Size
// Create The Window
if (!(hWnd=CreateWindowEx( dwExStyle, // Extended Style For The Window
"OpenGL", // Class Name
title, // Window Title
dwStyle | // Defined Window Style
WS_CLIPSIBLINGS | // Required Window Style
WS_CLIPCHILDREN, // Required Window Style
0, 0, // Window Position
WindowRect.right-WindowRect.left, // Calculate Window Width
WindowRect.bottom-WindowRect.top, // Calculate Window Height
NULL, // No Parent Window
NULL, // No Menu
hInstance, // Instance
NULL))) // Dont Pass Anything To WM_CREATE
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return false; // Return FALSE
}
static PIXELFORMATDESCRIPTOR pfd= // pfd Tells Windows How We Want Things To Be
{
sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
1, // Version Number
PFD_DRAW_TO_WINDOW | // Format Must Support Window
PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
PFD_DOUBLEBUFFER, // Must Support Double Buffering
PFD_TYPE_RGBA, // Request An RGBA Format
24, // Select Our Color Depth
0, 0, 0, 0, 0, 0, // Color Bits Ignored
0, // No Alpha Buffer
0, // Shift Bit Ignored
0, // No Accumulation Buffer
0, 0, 0, 0, // Accumulation Bits Ignored
24, // 24Bit Z-Buffer (Depth Buffer)
0, // No Stencil Buffer
0, // No Auxiliary Buffer
PFD_MAIN_PLANE, // Main Drawing Layer
0, // Reserved
0, 0, 0 // Layer Masks Ignored
};
if (!(hDC=GetDC(hWnd))) // Did We Get A Device Context?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return false; // Return FALSE
}
if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd))) // Did Windows Find A Matching Pixel Format?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return false; // Return FALSE
}
if(!SetPixelFormat(hDC,PixelFormat,&pfd)) // Are We Able To Set The Pixel Format?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return false; // Return FALSE
}
if (!(hRC=wglCreateContext(hDC))) // Are We Able To Get A Rendering Context?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return false; // Return FALSE
}
if(!wglMakeCurrent(hDC,hRC)) // Try To Activate The Rendering Context
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return false; // Return FALSE
}
ShowWindow(hWnd,SW_SHOW); // Show The Window
SetForegroundWindow(hWnd); // Slightly Higher Priority
SetFocus(hWnd); // Sets Keyboard Focus To The Window
reshape(width, height); // Set Up Our Perspective GL Screen
init();
return true; // Success
}
The WS_OVERLAPPEDWINDOW style includes the WS_THICKFRAME style which, I think, is responsible for making your window resizeable.
Consider something like
dwStyle=(WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX);
You can use WS_OVERLAPPEDWINDOW ^ WS_THICKFRAME
The XOR will keep everything in WS_OVERLAPPEDWINDOW except for WS_THICKFRAME
You can try something like this:
::SetWindowLong(hWnd, GWL_STYLE, GetWindowLong(hWnd, GWL_STYLE)&~WS_SIZEBOX);
It only disable resizing by dragging the edge of windows.
By the way, WS_SIZEBOX is the same as WS_THICKFRAME because of
#define WS_SIZEBOX WS_THICKFRAME
If you use WS_OVERLAPPED | WS_MINIMIZEBOX | WS_SYSMENU, it disable both maximizing and resizing.
Change your window style from WS_OVERLAPPEDWINDOW to, say, WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX. In other words, it's overlappedwindow minus the thickframe (resizable border) and the maxbox.
Process the WM_SIZING message and override all attempts to change the window's rectangle.
For MFC,
Go to Properties > Border and set to "Dialog Frame"
It worked for me since the previous setting of the Border was set to "Resizing"
You could also try removing WS_OVERLAPPEDWINDOW and replace with WS_MINIMIZEBOX|WS_SYSMENUL
That works for me, but instead of using
WS_OVERLAPPEDWINDOW & ~WS_THICKFRAME
use only
WS_OVERLAPPEDWINDOW