In my current project I am working on I would like to make the opengl viewport window resize from when the user resizes the drag window ("SizeBox"), I planned on using the windows "ENTERSIZEMOVE" function from the windows.h window api to get the signal to redraw the viewport.I would then call "UpdateRender" to update my viewport.
On running my program I only seem to get one update call to resize the window (even if I stop and start dragging again),I also have a cube in the scene which is rotating it is entered (0.0f,0.0f,10.of). I wanted the cube to move along with the window "resizing" instead of it getting covered over by the window,Since the cube is set to the centre of the viewport so if I am correct I should not need to move it via a gltransform.
If anyone has any thoughts on why I am not getting a constant viewport "refresh" from the window being dragged it would be much appreciated.
Message loop handler (snippet)
{ case WM_ENTERSIZEMOVE:
render->UpdateRender();
break;
}
Update Render
void Render::UpdateRender()
{
int update_x = rect.right - rect.left;
int update_y = rect.bottom - rect.top;
glViewport(0,0 ,update_y/2,update_x/2);
}
Create Window
int window::Wincreate(HINSTANCE hInstance, char *winname, int winwidth, int winheight)
{
Hwnd = CreateWindow("Game Engine", winname, WS_VISIBLE | WS_SYSMENU | WS_SIZEBOX | WS_MAXIMIZEBOX | WS_MAXIMIZE, 0, 0, winwidth , winheight , 0, 0, hInstance, 0);
if (!Hwnd)
{
MessageBox(0, "Error: Could not Create Window", "Error", MB_OK);
}
Engine->EnableOGLAPI();
Draw->Initalize();
return 0;
}
Main application Loop
int window::Winloop(MSG msg)
{
while (running)
{
if (PeekMessage(&msg,0,0,0,PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
angle++;
Draw->MainRender();
SwapBuffers(hDC);
}
}
return 0;
}
Related
I'm trying to attach a glfw window to an electron one.
I've succesfully retrieved the electron window handle (electronWindow.getNativeWindowHandle()) in my glfw app, and then used win32 api to try and attach them to one another :
GLFWwindow* createWindow(HWND parentWindow)
{
// Create an invisible window
fprintf(stdout, "Creating window as child of window 0x%016x\n", parentWindow);
glfwDefaultWindowHints();
glfwWindowHint(GLFW_RESIZABLE, FALSE);
glfwWindowHint(GLFW_DECORATED, GLFW_FALSE);
glfwWindowHint(GLFW_VISIBLE, GLFW_TRUE);
GLFWwindow* window = glfwCreateWindow(800, 600, "", nullptr, nullptr);
// That we attach as a child to an other one
HWND hw = glfwGetWin32Window(window);
HWND previousParent = SetParent(hw, parentWindow);
if (!previousParent) {
fprintf(stderr, "Couldn't set window parent: %s\n", lastWindowsError().c_str());
glfwDestroyWindow(window);
return nullptr;
}
ShowWindow(hw, SW_SHOW);
return window;
}
The SetParent call doesn't fail so I'm assuming the connection is made.
Then I have my (very classical) main glfw loop like this :
while (!glfwWindowShouldClose(window))
{
glClearColor(0.3, 0.4, 0.8, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
glfwPollEvents();
glfwSwapBuffers(window);
}
So the "faulty" behavior I've got is the following :
The electron app freezes. Nothing moves, the process is "not responding"
My glfw window doesn't show up anywhere
I haven't done an win32 event handling on glfw side, could this be the issue ? Like some specific event I have to take care of ?
Is this an issue with the electron app not passing events to the glfw window, hence blocking everything ?
Note: I'm doing this because I want to display native opengl using a pre-existing engine we've got.
I've tried naively doing glfwSetWindowPos each time the electron window moves, but it's sluggish as hell (probably Windows preventing this behavior) so I'm trying other approaches (here : attaching the opengl window as a child of electron).
So it seems it's not a very good idea haha + I'm not that good with win32 api so I can't really tell what's not working (cf. #iinspectable comments)
I delved into this issue on electron's github : https://github.com/electron/electron/issues/10547 and found a way to display an OpenGL frame on top of an Electron window.
I circumvented the issue by creating the window as a child process of the electron app with the HWND as startup argument :
const { app, BrowserWindow } = require('electron')
const { endianness } = require('os')
const { spawn } = require('child_process')
const nativeExecutablePath = 'src/overlay/build/Release/kf-overlay.exe'
const indexPath = 'src/ui/html/index.html'
const startChildProcess = (hwnd, target) => {
const data = endianness() == 'LE'
? hwnd.readInt32LE()
: hwnd.readInt32BE()
const p = spawn(target, [data], { cwd: process.cwd() })
p.stdout.on('data', data => console.log(`[native] ${data}`))
p.stderr.on('data', data => console.log(`[native] ${data}`))
}
const createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600
})
// win.loadFile(indexPath)
win.loadURL('https://www.google.com')
win.webContents.setFrameRate(60)
console.log(`Starting child process ${nativeExecutablePath}`)
const hwnd = win.getNativeWindowHandle()
startChildProcess(hwnd, nativeExecutablePath)
}
app.whenReady().then(() => {
createWindow()
})
Then creating the window as a child from C++ side :
HWND createChildWindow(HWND parent)
{
RECT rect;
GetWindowRect(parent, &rect);
int parentWidth = rect.right - rect.left;
int parentHeight = rect.bottom - rect.top;
DWORD style = WS_VISIBLE | WS_CHILD | WS_POPUP;
auto child = CreateWindowEx(
WS_EX_LAYERED | WS_EX_TOPMOST | WS_EX_TRANSPARENT | WS_EX_COMPOSITED,
WINDOW_CLASS_NAME,
nullptr,
style,
parentWidth / 2 - 512,
parentHeight / 2 - 512,
512,
512,
parent,
nullptr,
nullptr,
nullptr
);
SetParent(child, parent);
return child;
}
Finally I could create the OpenGL context through wglCreateContext calls, and render a frame with OpenGL calls :)
I'm trying to place dialog window adjacent to desktop's top or bottom border.
Code:
CRect MonitorWorkingArea(HMONITOR monitor)
{
MONITORINFOEX monInfo;
zeroVar(monInfo);
monInfo.cbSize = sizeof(monInfo);
GetMonitorInfo(monitor, &monInfo);
return monInfo.rcWork;
}
CRect MonitorWorkingArea_Wnd(HWND hwnd)
{
return MonitorWorkingArea(MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST));
}
CRect MonitorWorkArea_Wnd(CWnd& wnd)
{
return MonitorWorkingArea_Wnd(wnd.GetSafeHwnd());
}
void CMyDialog::SetDefaultWndPos(bool toBottom)
{
// Here we can be sure, that
// a) parent of this window is not null, is visible, not minimized
// b) this window smaller than working area of desktop
// c) it has WS_POPUP style
CRect rcThis;
GetWindowRect(&rcThis);
// Shift our rectangle to most upper or most bottom position
const CRect rcDesktop = MonitorWorkingArea_Wnd(*this);
rcThis.MoveToY(toBottom ? rcDesktop.bottom - rcThis.Height() : 0);
// Move window
SetWindowPos(NULL, rcThis.left, rcThis.top, 0, 0,
SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
}
Real code is bit more complex, I omit some checks and features for simplicity.
I have two monitors, both are 1920×1080 and in virtual coordinate space they are laying on:
Primary: (0,0) — (1920,1080)
Secondary: (1920,0) — (3840, 1080)
Code above works fine when window placed on primary monitor, but on secondary one it's works unexpectedly: it centers window based on it's parent.
For instance I'm calling SetDefaultWndPos(false) and rcThis being calculated as {left:2710, top:0, right:3423, bottom:550}. So SetWindowPos is called with zero y:
SetWindowPos(NULL, 2710, 0, 0, 0,
SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
But in handler of WM_WINDOWPOSCHANGING
void CMyDialog::OnWindowPosChanging(WINDOWPOS* lpwndpos)
{
__super::OnWindowPosChanging(lpwndpos);
}
I see in debug x = 2710 (unchanged) and y = 475 (unexpected). Next I check dialog's y-position in Spy utility, it's 475. Dialog window looks like it was centered on it's parent window.
All it looks like an OS errorneously detected requested window position as out-of-desktop and used some default positioning.
Only workarund I found is to decrease desktop working area on 1 pixel from each side:
CRect MonitorWorkingArea(HMONITOR monitor)
{
MONITORINFOEX monInfo;
zeroVar(monInfo);
monInfo.cbSize = sizeof(monInfo);
GetMonitorInfo(monitor, &monInfo);
CRect rc = monInfo.rcWork;
if( !(monInfo.dwFlags & MONITORINFOF_PRIMARY) )
{
++rc.left;
++rc.top;
--rc.right;
--rc.bottom;
}
return rc;
}
It works but looks as strange ugly hack.
Can anybody explain what happens here and help me with good decision?
Can it be OS version dependent? (I use Windows 7 Professional SP1).
I have a program that puts a transparent window on top of the desktop where a user can do some free hand drawing with the mouse. The program works fine as long as Aero is enabled but when Aero is disabled (on Windows 7) it fails - I cannot draw and the mouse doesn't change to the mouse shape I set for the window.
The code looks like this (MFC):
//=============================================================================
// PreCreateWindow
//-----------------------------------------------------------------------------
// Public function to create the window based on global properties
//=============================================================================
BOOL CDrawWnd::PreCreateWindow(CREATESTRUCT& cs)
{
HBRUSH hBgBrush = ::CreateSolidBrush(m_crBackgroundColor);
HCURSOR hcursor = NULL;
if (m_uiCursor)
hcursor = AfxGetApp()->LoadCursor(m_uiCursor);
else if (m_Cursor)
hcursor = AfxGetApp()->LoadStandardCursor(m_Cursor); // By default IDC_CROSS
try
{
cs.lpszClass = AfxRegisterWndClass(CS_HREDRAW | CS_VREDRAW, hcursor, hBgBrush);
}
catch(.../*CResourceException ex*/)
{
/*ex.ReportError();*/
MessageBox(_T("AfxRegisterWndClass failed"));
}
return CWnd::PreCreateWindow(cs);
}
//=============================================================================
// CreateWnd
//-----------------------------------------------------------------------------
// Public function to create the window based on global properties
//=============================================================================
bool CDrawWnd::CreateWnd()
{
CreateEx(WS_EX_LAYERED | WS_EX_TOPMOST | WS_EX_TOOLWINDOW, _T("WsmLayeredWindowClass"), _T("Layered Draw Window"), WS_POPUP, m_StartWndRect, NULL, NULL, NULL);
if (m_hWnd)
{
// Make this window transparent
if (!SetLayeredWindowAttributes(m_crBackgroundColor, (255 * m_Transparency) / 100, LWA_COLORKEY))
{
TRACE(_T("\nSetLayeredWindowAttributes failed: 0x%lX"), GetLastError());
}
ShowWindow(SW_SHOW);
GetWindowRect(&m_rDrawingSurface);
return true;
}
return false;
}
CDrawWnd is derived from CWnd. CDrawWnd::CreateWnd() is called to create the window. In the case it doesn't work
SetLayeredWindowAttributes(m_crBackgroundColor, (255 * m_Transparency) / 100, LWA_COLORKEY)
fails even though GetLastError() returns 0.
In a C++ app I create a button using CreateWindowEx and later try to change its position using SetWindowPos, but the button doesn't appear where I want it.
What's interesting is that when I resize the window (with the mouse, not programatically), I can see for a split second a blank silhouette the same size of the button where the button is supposed to appear. This must be because I also call SetWindowPos in response to window resizing events. However the actual button stays at the same location. I'd post a screenshot but for some reason the silhouette never shows up in screenshots.
This is the code that changes the X position (the code that changes the Y position is almost identical):
HRESULT Control::put_Left(float left)
{
RECT windowRect;
::GetWindowRect(m_hWnd, &windowRect);
if (m_isTopLevel)
{
BOOL bResult = ::SetWindowPos(
m_hWnd,
nullptr,
static_cast<int>(DesktopDpi::GetInstance().DipsToPixelsX(left)),
windowRect.top,
0,
0,
SWP_NOSIZE | SWP_NOZORDER | SWP_NOREPOSITION
);
if (!bResult)
return HRESULT_FROM_WIN32(::GetLastError());
}
else
{
// NOTE: for a button this is the code that will execute, because a
// button is not a top-level window
HWND hWndParent = ::GetParent(m_hWnd);
if (hWndParent == nullptr)
return HRESULT_FROM_WIN32(::GetLastError());
POINT parentPos = {0, 0};
if (!::ClientToScreen(hWndParent, &parentPos))
return E_FAIL;
BOOL bResult = ::SetWindowPos(
m_hWnd,
nullptr,
static_cast<int>(DesktopDpi::GetInstance().DipsToPixelsX(left)),
windowRect.top - parentPos.y,
0,
0,
SWP_NOSIZE | SWP_NOZORDER | SWP_NOREPOSITION
);
if (!bResult)
return HRESULT_FROM_WIN32(::GetLastError());
}
return S_OK;
}
Are you sure the parent of the button isn't moving it back to the old position when it handles WM_SIZE? It sure sounds like it from your description.
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.