Using DirectX 9, I am unable to acquire the keyboard device if another program has focus while my program is trying to acquire it. This is a problem if the user clicks another window while my program is initializing.
I call Windows's SetFocus and SetCapture functions, but it doesn't seem to have an effect.
#define FAILED(hr) (((HRESULT)(hr)) < 0) //in WinError.h
...
class CantCreate {}; //My exception class
Keyboard::Keyboard(LPDIRECTINPUT8 pDI, HWND hwnd)
{
LPDIRECTINPUTDEVICE8 m_pDIDev;
if (FAILED(pDI->CreateDevice(GUID_SysKeyboard, &m_pDIDev, NULL)))
throw CantCreate();
if (FAILED(m_pDIDev->SetDataFormat(&c_dfDIKeyboard)))
throw CantCreate();
if(FAILED(m_pDIDev->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE)))
throw CantCreate();
SetFocus (hwnd); SetCapture (hwnd);
if (FAILED(m_pDIDev->Acquire())) throw CantCreate(); //<-- throws an exception here
}
I've also tried replacing that last line with
while (FAILED(m_pDIDev->Acquire())) { SetFocus (hwnd); SetCapture (hwnd); }
...but it never does seize focus.
What's the best way either to seize focus, or to acquire the keyboard without needing focus?
Based on discussion from the answer below, I tried this so that it could wait for focus:
while (true)
{
while (GetFocus () != hwnd) Sleep (100);
if (! FAILED(m_pDIDev->Acquire())) break;
}
Sometimes it works beautifully. Sometimes the application freezes.
That is a security feature, not a weakness.
If programs could seize the keyboard, think what a pain it would be to exit malware you did not want to run.
Sleep awhile between attempts. Once the focus is changed to your app, then you are allowed to do what you need.
Related
I've 2 mfc buttons that I want to hide when a 3D stl file is being loaded and then show the buttons again when the stl loading is complete. This is to prevent user from re-loading the model when the loading is currently taking place.
The snippet of the code is as below
{ // change control state when model loads
((CButton *)this->GetDlgItem(IDC_RELOAD_STOCK_BUTTON))->ShowWindow(SW_HIDE);
((CButton *)this->GetDlgItem(IDOK))->ShowWindow(SW_HIDE);
UpdateWindow();
}
// this process takes few seconds to load the file in the memory
customStockModel.LoadFile(pathName.GetBuffer(pathName.GetLength()));
{
// change control state when the model has loaded
((CButton *)this->GetDlgItem(IDC_RELOAD_STOCK_BUTTON))->ShowWindow(SW_SHOW);
((CButton *)this->GetDlgItem(IDOK))->ShowWindow(SW_SHOW);
UpdateWindow();
}
The buttons do get hidden and reappear as I expect, but when I click the button area while it's hidden, the onclick handler gets called immediately when the button control reappears on the screen. it seems like the click message is queued and mfc calls the handler once the buttons are activated. What am I doing wrong here?
Ideally you should read your file in a thread - this would allow your application to refresh itself normally and process messages.
Now if you are unsure about this (multi-threading is hard), you can call regularly the following function in your lenghty function to clear up the message loops.
BOOL YourClass::DoEvents()
{
MSG msg;
while (::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if (msg.message == WM_QUIT)
{
return FALSE;
}
if (!AfxGetApp()->PreTranslateMessage(&msg))
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
}
return TRUE;
}
It will work but "proper programmers" will scream when they see this!
Good luck
I have a windowless program that handles some window management hotkeys. I'd like to provide features such as the ability to move a window between monitors. I've used EnumDisplayMonitors to enumerate all existing monitors in the system, and I've written code to handle WM_DEVICECHANGE, but I'm not actually receiving the message.
Here's my message loop:
// I've tried GetMessage(&msg, (HWND) NULL, 0, 0) here too
while (GetMessage(&msg, (HWND) -1, 0, 0) > 0)
{
int key;
int mod;
MessageBox(NULL, (LPCWSTR) ((std::wostringstream&) (std::wostringstream() << L"You got a message: " << msg.message)).str().c_str(), L"Got Message", MB_OK);
switch (msg.message)
{
case WM_HOTKEY:
key = HIWORD(msg.lParam);
mod = LOWORD(msg.lParam);
if (mod != MOD_WIN) continue;
ProcessHotkey(key);
break;
case WM_DEVICECHANGE:
InitMonitorInfo();
}
}
The program compiles and runs fine, and the hotkeys work. Upon adding or removing a monitor though, nothing happens. The message box to indicate a message has been received never appears.
I suppose I could just poll the monitor configuration every 5 seconds, but that's not the right way to solve the problem.
Do I need to actually create a window to receive WM_DEVICECHANGE? Because I don't. The hotkeys post their messages to NULL when they fire since they're not bound to a window, to be handled by the main thread.
You must create a window to get the WM_DEVICECHANGE message.
WM_DEVICECHANGE is a message that's broadcast, SendMessage(HWND_BROADCAST,...) style. Only top-level windows can receive it. The window doesn't need to be visible so there's little reason to look for an alternative.
RegisterDeviceNotification() is an alternative. But that still needs a window. Or a service handle, but you don't want to move windows around from a service. They run in an isolated session with their own desktop. So creating a window is a hard requirement.
I want to make program work while handle is available. I thinking about setting timer on initialization... and insert all source of program in to it, but if I got lost handle when program processing in while loop it will not let me close dialog box immediately.
BOOL WaitProcessDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
SetTimer(IDC_PROGRESS1, 0, NULL);
return TRUE;
}
void WaitProcessDlg::OnTimer(UINT nIDEvent)
{
if(::FindWindow(NULL, str)){
tempHWND = ::FindWindow(NULL, str);
while(tempHWND){
----------------------->>>>>>>>>>>> A LOT OF CODING <<<<<<<<<<<<<<<<----------------------
}
EndDialog( 0 );
KillTimer(IDC_PROGRESS1);
}
CDialog::OnTimer(nIDEvent);
}
So my question is what the best way to close dialog when handle of external application may lost, maybe insert thread or there are any other way to do that?
It sounds like you need a windows hook.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms644959(v=vs.85).aspx#whgetmessagehook
with WH_GETMESSAGE you get to see the windows events being processed by the other application's window, you could then wait for the WM_CLOSE to show up, and kill your dialog.
The main form opens a child form that has a handful of button CONTROLs on it. I need to trap keyboard events so I subclassed one of the controls. All is good until the control loses focus of course.
Ideally, as long as this child form is open I would like to assign the focus to this control and thus trap all the keystrokes, no matter where the user clicks.
I suspect superclassing might be a better way to go but I am not as familiar with it.
Perhaps what I should do is use accelerators on the main form?
ADDED:
I should mention that the main form has a large listview control that is subclassed to recover up/down arrows and mousewheel etc.
The traditional way is to install a keyboard hook (SetWindowsHookEx), but you need to inject it into every application, and it doesn't work across 32/64 bit boundaries.
What you can do however, and quite easily at that, is to poll the keyboard with GetKeyboardState on a timer and check whether your f1-f12 keys are activated. The timer can be as slow ticking as 100ms and it will catch almost everything while using virtually no resources.
Assuming that this is within Windows and the Win32 API, one option is to look for messages in your main GetMessage, TranslateMessage, DispatchMessage loop. You can special-case any message within this loop, irrespective of which window it's aimed at.
You should probably use IsChild to check that the message is intended for a control on your main window (as opposed to some dialog box or message box that might be displayed separately). Getting the logic right can be fiddly, too. It would be best to only intercept messages when you know your control has lost the focus, and only intercept the exact messages you need to.
Years ago, I wrote a library message loop with a lot of this built in. I had a simple manager class that held pointers to instances of my own little window class. The loop knew the difference between dialogs and normal windows, gave each window class a chance to spy on its childrens messages, and so on. You won't be able to run this directly and the conventions are a bit strange, but you might find this useful...
int c_Window_List::Message_Loop (void)
{
MSG msg;
bool l_Handled;
while (GetMessage (&msg, NULL, 0, 0))
{
l_Handled = false;
c_Windows::c_Cursor l_Cursor;
bool ok;
for (ok = l_Cursor.Find_First (g_Windows); ok; ok = l_Cursor.Step_Next ())
{
if (IsChild (l_Cursor.Key (), msg.hwnd))
{
if (l_Cursor.Data ().f_Accelerators != NULL)
{
l_Handled = TranslateAccelerator (l_Cursor.Key (), l_Cursor.Data ().f_Accelerators, &msg);
if (l_Handled) break;
}
if (l_Cursor.Data ().f_Manager != 0)
{
l_Handled = l_Cursor.Data ().f_Manager->Spy_Msg (l_Cursor.Key (), msg);
}
if (l_Handled) break;
if (l_Cursor.Data ().f_Is_Dialog)
{
l_Handled = IsDialogMessage (l_Cursor.Key (), &msg);
if (l_Handled) break;
}
}
}
if (!l_Handled)
{
TranslateMessage (&msg);
DispatchMessage (&msg);
}
if (g_Windows.Size () == 0)
{
// When all windows have closed, exit
PostQuitMessage (0);
}
}
return msg.wParam;
}
The f_ prefixes mean field - I picked up the m_ convention later, but this code hasn't been revisited in a very long time. f_Manager in particular points to an instance of my c_Window_Base class. The c_Cursor class is a kind of iterator, used to step through all the windows stored in the g_Windows variable (actually a static class member rather than a global).
My application (the bootstrap application for an installer that I'm working on needs to launch some other applications (my installer and third party installers for my installer's prerequisites) and wait for them to complete. In order to allow the GUI to do screen updates while waiting for an app to complete, I put a message pump in the wait loop using the 'MFC-compatible' example in the Visual Studio documentation on idle loop processing as a guideline. My code (which is in a member function of a CWinApp-derived class) is as follows:
if (::CreateProcess(lpAppName, szCmdLineBuffer, NULL, NULL, TRUE, 0, NULL, NULL,
&StartupInfo, &ProcessInfo))
{
::GetExitCodeProcess(ProcessInfo.hProcess, &dwExitCode);
if (bWait)
while (dwExitCode == STILL_ACTIVE)
{
// In order to allow updates of the GUI to happen while we're waiting for
// the application to finish, we must run a mini message pump here to
// allow messages to go through and get processed. This message pump
// performs much like MFC's main message pump found in CWinThread::Run().
MSG msg;
while (::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))
{
if (!PumpMessage())
{
// a termination message (e.g. WM_DESTROY)
// was processed, so we need to stop waiting
dwExitCode = ERROR_CANT_WAIT;
::PostQuitMessage(0);
break;
}
}
// let MFC do its idle processing
LONG nIdle = 0;
while (OnIdle(nIdle++))
;
if (dwExitCode == STILL_ACTIVE) // was a termination message processed?
{
// no; wait for .1 second to see if the application is finished
::WaitForSingleObject(ProcessInfo.hProcess, 100);
::GetExitCodeProcess(ProcessInfo.hProcess, &dwExitCode);
}
}
::CloseHandle(ProcessInfo.hProcess);
::CloseHandle(ProcessInfo.hThread);
}
else
dwExitCode = ::GetLastError();
The problem that I'm having is that, at some point, this message pump seems to free up window and menu handles on the window that I have open at the time this code is run. I did a walk through in the debugger, and at no time did it ever get into the body of the if (!PumpMessage()) statement, so I don't know what's going on here to cause the window and menu handles to go south. If I don't have the message pump, everything works fine, except that the GUI can't update itself while the wait loop is running.
Does anyone have any ideas as to how to make this work? Alternatively, I'd like to launch a worker thread to launch the second app if bWait is TRUE, but I've never done anything with threads before, so I'll need some advice on how to do it without introducing synchronization issues, etc. (Code examples would be greatly appreciated in either case.)
I've also posted this question on the Microsoft forums, and thanks to the help of one Doug Harris at Microsoft, I found out my problem with my HWND and HMENU values was, indeed due to stale CWwnd* and CMenu* pointers (obtained using GetMenu() and GetDialogItem() calls. Getting the pointers again after launching the second app solved that problem. Also, he pointed me to a web site* that showed a better way of doing my loop using MsgWaitForMultipleObjects() to control it that doesn't involve the busy work of waiting a set amount of time and polling the process for an exit code.
My loop now looks like this:
if (bWait)
{
// In order to allow updates of the GUI to happen while we're
// waiting for the application to finish, we must run a message
// pump here to allow messages to go through and get processed.
LONG nIdleCount = 0;
for (;;)
{
MSG msg;
if (::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))
PumpMessage();
else //if (!OnIdle(nIdleCount++))
{
nIdleCount = 0;
if (!PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))
{
DWORD nRes = ::MsgWaitForMultipleObjects(1, &ProcessInfo.hProcess,
FALSE, INFINITE, QS_ALLEVENTS);
if (nRes == WAIT_OBJECT_0)
break;
}
}
}
}
::GetExitCodeProcess(ProcessInfo.hProcess, &dwExitCode);
*That Web site, if you're curious, is: http://members.cox.net/doug_web/threads.htm
I think your problem is in WaitForSingleObject
Looking in MSDN you see this
Use caution when calling the wait functions and code that directly or indirectly creates windows. If a thread creates any windows, it must process messages. Message broadcasts are sent to all windows in the system. A thread that uses a wait function with no time-out interval may cause the system to become deadlocked. Two examples of code that indirectly creates windows are DDE and the CoInitialize function. Therefore, if you have a thread that creates windows, use MsgWaitForMultipleObjects or MsgWaitForMultipleObjectsEx, rather than WaitForSingleObject.
In my code in the message pump use use MsgWaitForMultipleObjects (doc).
With a call this call.
MsgWaitForMultipleObjects(1, &ProcessInfo.hProcess, FALSE, 100, QS_ALLEVENTS);
This should stop your problem with the resources dissapearing.
When you say that window and menu handles seem to be being freed, do you mean that you've got actual HWND and HMENU values that no longer seem to work, or have you got MFC CWnd* and CMenu* variables that fail?
If the latter, the problem is most likely that you're getting the CWnd* pointers by calling CWnd::FromHandle() (or CMenu::FromHandle()) somewhere (or calling something that calls them), and OnIdle() is discarding them.
The underlying reason is that MFC maintains a map from window (or menu, etc.) handles to CWnd* objects in the system. When CWnd::FromHandle() is called, it looks for a match in the map: if one is found, it's returned. If not, a new, temporary CWnd is created, added to the map, and returned. The idea behind OnIdle() is that when it's called all message processing is done, so OnIdle() discards any of these temporary CWnd objects that still exist. That's why the CWnd::FromHandle() documentation warns that the returned pointer may be temporary.
The "correct" solution to this is to not hang onto the CWnd* pointers returned from CWnd::FromHandle(). Given the simplicity of your application, it might be easier to just remove the call OnIdle(): this shouldn't have any negative effects on an installer.
Of course, this is all something of a guess, but it sounds plausible...
There is a Windows function called DisableProcessWindowsGhosting (see http://msdn.microsoft.com/en-us/library/ms648415(v=vs.85).aspx) that prevents Windows from 'ghosting' your window, and continue updating the window (your animation).