(I use Ogre3D for the rendering but the question should be generic.)
The problem: most 3D aplications use a cycle which iterates rendering a frame and checking for messages and processing them. However if a dialog is opened (MessageBox or similar), it blocks the execution of the thread and is running it's own message cycle, but it obviously does not call the 3D rendering function in it.
What is the preferred, or "best" way of keeping rendering the 3D scene even when dialogs are open? The normal applications do not suffer from this problem, because their re-rendering is handled by WM_PAINT messages and similar, and since modal dialogs do have internal message loop, the window proc get's called when needed and everything looks fine. In my 3D project however, "when needed" is all the time, because the window has to be updated, even without WM_PAINT messages.
The simple solution that comes to mind is to register a timer for the time when dialogs are open, and render 3D scene from the WindowProc, but is it really the best? Seems very dirty...
I don't know that this is the best way, but I think it will work.
Add a handler for WM_ENTERIDLE that uses PeekMessage to do something like:
case WM_ENTERIDLE:
while (!PeekMessage())
{
DoYourRendering();
}
return 0;
I would suggest having the code post a custom message to itself when entering the modal operation. You can then render the current frame when the modal loop dispatches the message, and then post another message to keep a rendering loop running. Once the modal operation finishes, you can stop posting messages to yourself and go back to your normal rendering logic. For menus, you can catch the WM_ENTERMENULOOP and WM_EXITMENULOOP messages to detect when the modal menu message loop begins and ends.
For example:
const UINT WM_RENDER_FRAME = WM_USER+100:
.
BOOL m_InModalOp = FALSE;
.
case WM_ENTERMENULOOP:
m_InModalOp = TRUE;
PostMessage(hwnd, WM_RENDER_FRAME, 0, 0);
break;
case WM_EXITMENULOOP:
m_InModalOp = FALSE;
break;
case WM_RENDER_FRAME:
if (m_InModalOp)
{
// render a frame...
PostMessage(hwnd, WM_RENDER_FRAME, 0, 0);
}
break;
.
m_InModalOp = TRUE;
PostMessage(hwnd, WM_RENDER_FRAME, 0, 0);
MessageBox(...);
m_InModalOp = FALSE;
Related
The status bar window of this program needs to be updated every time the user press a key that is likely to move the caret of the EDIT control, and the code below works like a charm! In a nutshell, pressing a key on the keyboard will update some values and send a message "ECM_GETLINEINFOS" that is next processed in the main window procedure (code below)
However, there is flickering that is not disturbing, of course, but I wonder if it's related to how I set the text on the status bar (maybe too many updates ?) or just a problem with the drawing part.
PS: The flickering occurs on the text, not the status bar in itself, so that is why I'm questioning how I should manage the update of my window.
constexpr int failed_val = -1;
LRESULT MainWindow::HandleMessage(UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
// Custom message sent by an EDIT control, I
// use this message to tell the status bar it must update its text.
case CEM_GETLINEINFO:
{
const size_t buffSz = 24;
std::wstring buffer(buffSz, L'\0');
int line = LOWORD(wParam);
int column = HIWORD(wParam);
int count = _snwprintf_s(buffer.data(), buffer.size(),
_TRUNCATE, L"Ln %d, Col %d", line, column);
if (count != failed_val) {
// Param 1 : The text to be displayed
// Param 2 : Which status bar part
m_statusBar->SetText(buffer, 0);
}
}
return 0;
}
}
Just as Flicker-Free Displays Using an Off-Screen DC directed by the answer said,
What makes this window flicker when we update it frequently? The
answer is that Windows asks the window procedure to repaint the window
as a two-step process. First, it sends a WM_ERASEBKGND message and
then a WM_PAINT message. The default handling for the WM_ERASEBKGND
message is to fill the area with the current window background color.
So the sequence of events is first to fill the area with solid color
and then to draw the text on top. The net result of doing this
frequently is that the window state alternates between its erased
state and its drawn stateāit flickers.
And
To prevent the control from flickering when we update it frequently,
we need to make two changes to how the control handles messages.
First, we need to prevent Windows from providing the default handling
of WM_ERASEBKGND messages. Secondly, we need to handle WM_PAINT
messages so that the background is painted with the window background
color and so that the changes to the control's client area happen at
once.
A status bar flicker free solution in .NET: Searching Visual Studio .NET style status bar. Or Simple Mode Status Bars could be enough.
I have a modeless dialog which I am showing and hiding programmatically from a worker thread. The problem is that the CWindow::ShowWindow(SW_SHOW) function is sometimes bringing the dialog to the front, and sometimes not.
Task: Show/Hide a simple logging & control window for an ATL COM object (dll) that runs in a separate thread. The COM object isn't a control: it is being used to wrap processing code for use in Excel VBA.
I've created a CMyDialog class derived from the CAxDialogImpl template. Then I'm using the CWorkerThread template for the worker thread. This is the Execute block (ie the function that runs in the worker thread).
HRESULT CLogProcessor::Execute(DWORD_PTR dwParam, HANDLE hObject)
{
m_bRunning = true; //Winging it as this isn't thread-safe, but I don't think that's the issue.
if (m_pDlg == 0)
{
m_pDlg = new CMyDialog(); //My dialog class
m_pDlg->SetStopEvent(m_hStopEvent); //Save the handle of the stop event in the Dialog class
m_pDlg->Create(NULL); //Create with no parent
m_pDlg->ShowWindow(SW_SHOW); //Show the window
}
//Loop here until told to stop by the Stop Event being signalled in the calling thread
while (WaitForSingleObject(m_hStopEvent, 0) == WAIT_TIMEOUT) //Polling Stop Event
{
//Have to keep the message loop going!
MSG uMsg;
while (PeekMessage(&uMsg, m_pDlg->m_hWnd, 0, 0, PM_REMOVE))
{
TranslateMessage(&uMsg);
DispatchMessage(&uMsg);
}
//The thread uses a protected "stack" of string messages to write to my logging window
string strMsg;
while (m_MsgStack.PopFront(strMsg))
{
std::wstring ws = std::wstring(strMsg.begin(), strMsg.end());
CWindow eb(m_pDlg->GetDlgItem(IDC_EDIT1));
eb.SendMessage(EM_REPLACESEL, 0, (LPARAM)ws.c_str());
}
}
//Stop event has been signalled so clear up the dialog
m_pDlg->DestroyWindow();
delete m_pDlg;
m_pDlg = 0;
m_bRunning = false;
return S_OK;
}
My Log object has two functions, StartLog() and StopLog() which are called by the COM object which is doing the main work of data processing.
void CLogProcessor::StartLog()
{
if (!m_bRunning)
{
::SetEvent(m_hStartEvent);
}
}
void CLogProcessor::StopLog()
{
if (m_bRunning)
{
::SetEvent(m_hStopEvent);
}
}
This works fine. I run VBA code in an Excel spreadsheet with buttons that call (via the COM object) StartLog() and StopLog(). The first time the Log Dialog appears all is good: it is activated and comes to the front. Firing StopLog() closes the dialog and it disappears. But the second time I call StartLog() the dialog window appears but it is not at the front, but behind other windows. I have tried a CWindow::BringWindowToTop() and/or SetFocus() call straight after the ShowWindow() but it makes no difference.
Another interesting feature is that my dialog has a system menu and so an 'X' to close it in the top-right hand corner. In the Dialog's message map, I am handling the WM_CLOSE message:
BEGIN_MSG_MAP(CMyDialog)
... Other entries
MESSAGE_HANDLER(WM_CLOSE, OnClose)
...
CHAIN_MSG_MAP(CAxDialogImpl<CMyDialog>)
END_MSG_MAP()
With OnClose() setting the Stop Event handle (previously passed to the Dialog object). Ie doing pretty much the same as the StopLog() function.
LRESULT CMyDialog::OnClose(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
::SetEvent(m_hStopEvent);
return 0;
}
If I close the log dialog with the mouse click, it goes away as before. BUT the next time I call StartLog() the dialog does what it is supposed to do and comes to the front, which is the action I want. So I replaced the StopLog() code with a SendMessage(WM_CLOSE) to my dialog: it closed the window, but again it did not reappear on top. Another difference is that using the Close X on the dialog means that the Dialog has the focus when it is closed. Closing it from the Excel button means that the Excel window has the focus.
I realize this is rather a long question, and thanks very much if you have soldiered down to the end! I'd been keen for any solution / insight.
Update: I didn't solve the problem as stated, just re-worked the code to use a modal Dialog box in the worker thread. When I am done with the dialog, I PostMessage(WM_CLOSE) from the main thread: the dialog ends and the worker thread finishes (having set an event to say it is done, so that the thread is not destroyed before the Dialog is cleaned up).
The dialog polls the stack of strings to display in response to a WM_USER+xxx message, posted from the main thread using PostMessage();
I still have the same issue that the dialog doesnt appear on top the second time I run the worker thread, but this time adding a ShowWindow(SW_SHOW) in the OnInitDialog() handler seems to bring the dialog to the top when it appears.
It also means I don't need my own message loop.
I need to prevent resizing of some items in a Win32 header control. No problem to process the HDN_BEGINTRACK notification message and cancel it - the problem is in the cursor indicating that the item can be resized. For instance, if the first item can't be resized, I see this:
, but I'd prefer to see this:
I can ignore the cursor change by suppressing the WM_SETCURSOR message, but the problem is how to know the header item WM_SETCURSOR is generated for. I can detect the item under the mouse pointer in WM_MOUSEMOVE using the HDM_HITTEST message, but WM_MOUSEMOVE is sent to window procedure only after WM_SETCURSOR. I analyzed all notification messages for the Win32 header control, and it seems, it does not have an equivalent of the MouseEnter event that is sent to the window procedure before WM_SETCURSOR.
Any ideas how to solve this problem?
You need to sub-class the header control if you haven't already.
In the sub-class, intercept the WM_SETCURSOR message, and use GetMessagePos() to get the coordinates of the mouse. These are in screen coordinates, so you need to convert them to client coordinates for the header control hit test.
// in the window sub-class
if (uMsg == WM_SETCURSOR)
{
DWORD dwPos = GetMessagePos();
HDHITTESTINFO hti;
hti.pt.x = GET_X_LPARAM(dwPos);
hti.pt.y = GET_Y_LPARAM(dwPos);
ScreenToClient(hWnd, &hti.pt);
SendMessage(hWnd, HDM_HITTEST, 0, reinterpret_cast<LPARAM>(&hti));
if (...) // test for items we want to block
{
SetCursor(LoadCursor(0, IDC_ARROW));
return TRUE;
}
// pass through to regular WndProc
}
I have a GUI window in WTL that runs inside a thread inside a CMessageLoop instance which has been added to the application instance and runs. Now, inside a button handler within the main GUI I create a new window. Once I click that button and create the window and try to post the quit message to the main GUI loop. The code:
Main window, has its own thread:
CMessageLoop theLoop;
_MyppModule.AddMessageLoop(&theLoop);
if(m_pMyDlg == NULL) {
m_pMyDlg = new CMyDlg();
if(!IsWindow(*m_pMyDlg))
{
m_pMyDlg->Create(NULL);
m_pMyDlg->ShowWindow(SW_SHOW);
nRet = theLoop.Run();
_MyppModule.RemoveMessageLoop();
}
}
Button handler & child window creation:
LRESULT CMyDlg::OnButtonClicked(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
ChildWindowDlg childDlg;
childDlg.Create(m_hWnd);
childDlg.ShowWindow(SW_SHOW);
CMessageLoop _loop;
);
_loop.Run();
::DestroyWindow(childDlg);
return S_OK;
}
Now, if I click the Close button in my MyDlg window the button's handler will get called, inside it I do ::PostQuitMessage but that never reaches the theLoop messageloop from the first code snippet.
This happens after I exit the second loop, so _loop gets destroyed and the child dialog is destroyed.
What is happening here?
You have two message loops here, the child's one is nested. On the other hand, the message queue is one per thread, and is pumped by the most inner message loop (with GetMessage). So, WM_QUIT message gets retrieved by the inner message loop inside CMyDlg::OnButtonClicked.
The second code snippet is totally unnatural. If your goal is to have a window popped up, then closed and and then you want to complete execution of your button click handler, then modal dialog is what you need:
LRESULT CMyDlg::OnButtonClicked(WORD wNotifyCode, WORD wID, HWND hWndCtl,
BOOL& bHandled)
{
ChildWindowDlg childDlg; // Add constructor parameters if needed
// Additional initlaization calls might go here
const INT_PTR nResult = childDlg.DoModal(m_hWnd); // DoModal handles it all
if(nResult == IDOK) { ... } // Hey's we even have result coming from `EndDialog`
return 0; // No S_OK here
}
No message loops, no PostQuitMessage, no separate window creation/destruction calls needed. This is what modal dialogs are for.
If you don't want to block "calling" window, and the idea is to have both master and slave windows running side by side (or, one is a part of another, anyway both to be responsive at the same time), then you don't want to block your message handler. The handler will create window and set it up (.Create, .ShowWindow) and then exit from OnButtonClicked function.
Both windows are created, both are alive and have their message sent to them by top level message loop. This is the correct approach, you don't normally need more than one message loop per thread. Sometimes it might make sense for specific operations, but this is really rare. Windows are passive instances. They respond to messages with their message handlers. A thread message loop serves all thread windows, because what it does is DispatchMessage API call, which in turn looks for target window, takes its WndProc and calls it handing message details in.
I noticed that in Windows, if you maximize a window you can not resize it until you un-maximized it again. This appears to be a normal behaviour, so I would like to remove my resize gripper when the window is maximised.
At the moment I can't find a property to detect if a window is maximized, and although I could add a boolean in my controller, it wouldn't necessarily catch requests to maximize from the OS.
So if you know of a reliable way to test if a window is maximized please let me know.
On a related note, I am using custom chrome, and when I maximize a window it overlaps the windows task bar. I can think of hacks to detect available screen size (using a transparent system chrome window), but it would be good to know of a better method.
Thanks
Rob
In your application (MXML) on the in the init method you ussually call on creationComplete:
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
creationComplete="init()" >
Add the following code:
this.addEventListener(NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGE, trackState);
the method looks like this:
public function trackState(event:NativeWindowDisplayStateEvent):void
{
if (event.afterDisplayState == NativeWindowDisplayState.MAXIMIZED)
{
isMaximised = true;
} else {
isMaximised = false;
}
}
I have figured out how this can best be done thanks to some pointers from TheBrain.
Firstly you need to watch for resize events to the window your want to control:
NativeApplication.nativeApplication.activeWindow.addEventListener(NativeWindowBoundsEvent.RESIZE, onWindowResize);
Then handle that event to decide if the window is maximised or not:
public function onWindowResize(event:NativeWindowBoundsEvent):void
{
if (event.afterBounds.height >= Screen.mainScreen.visibleBounds.height && event.afterBounds.width >= Screen.mainScreen.visibleBounds.width)
isMaximised = true;
else
isMaximised = false;
}
You then need to catch or create your own maximize button, and when clicked perform the following code:
if (isMaximised)
{
var bounds:Rectangle = Screen.mainScreen.visibleBounds;
NativeApplication.nativeApplication.activeWindow.bounds = bounds;
}
else
{
NativeApplication.nativeApplication.activeWindow.bounds = new Rectangle(100, 100, 500, 600);
}
You can modify the bounds to over maximize (which is handy for custom chrome windows with shadows), and you can also set the application to reset to a default size if the maximize button is clicked when it's already maximized (or do nothing).
I had issues about when to assign the window resize listner, and ended up removing and adding it every time the maximize button was clicked. It's a bit of overkill, but not too bad.
There is Win32 API Call that will do this for you:
BOOL IsZoomed( HWND hWnd );
to get the actual usable space from the screen, use the flash.display.Screen class, or you can use the systemMaxSize() which returns the largest window size allowed by the OS. For maximization you have some events that the window is dispaching when maximized/minimized/restored. You can find more info on the adobe pages (the link under systemMaxSize).
To detect if window is maximized...I don't think there is such a function (I might be wrong) but you can test if the app size is equal with the available screen size which means it's maximized. Or hook on the resize event which is triggered when the app is maximized/minimized/resized
Here is an easier way of checking if a window is maximized:
if(stage.nativeWindow.displayState == NativeWindowDisplayState.MAXIMIZED)
{
//do something
}
The following worked for me. No need to set event listeners, this code can be used to check the real-time state of the native window:
if (nativeWindow.displayState == 'maximized')
{
trace('Maximized');
}
else
{
trace('Minimized');
}
Can you use something like this to hook the maximize() event?