Attach a repetitive timer to Different code bases - c++

My application has 2 parts, one is a MFC based window, while the other is a C++ based code.
I need to have a timer attached to both these parts, that would trigger a behaviour at repeated intervals.
I used to be able to do this easily with QTimer, when I had worked with Qt.
With MFC/C++ I'm not sure what to use. Would a single setTimer() suffice, and how would the message handler look like in the C++ part of the code?
Kindly suggest how to attach one timer which would work with both these sections.
Thanks.

You cannot have a single timer invoke more than one action. If you want an expired timer to result in more than one action you will have to trigger all those actions from a single timer handler.
To set up a timer you can use SetTimer. You get to decide whether an expired timer posts a WM_TIMER message or calls a callback routine instead. Either way you can trigger whichever actions you desire.
How you implement the communication is up to you. The details you provide in your question are vague. Windows does not know or care what C++ is. Saying that part of your application is C++ based code does not help much. I'm sure the MFC part is C++ based as well.

SetTimer only works with a window. What you refer to as the C++ part of the code cannot have a message handler unless it creates a window to receive messages.

Related

How CWinThread::OnIdle is used?

As you know, OnIdle can be specified in MFC UI thread. For details, you can read this reference http://msdn.microsoft.com/en-us/library/1sa2f19f.aspx. But I am not sure how it can be used in practice.
According to the reference above,
"OnIdle is called in the default message loop when the thread's message queue is empty. Use your override to call your own background idle-handler tasks."
So I can understand that when the UI thread is not busy, the method is called. According to the documentation above,
"Because the application cannot process messages until OnIdle returns, do not perform lengthy tasks in this function."
But what tasks can be done in the idle event? A single example would suffice. Thanks
UPDATE: One discouraging fact is that this old (1996) article by Russell Weisz, titled "First Aid for the Thread-Impaired: Using Multiple Threads with MFC." was very helpful to understand CWinThread.
UPDATE2: As Microsoft removed the MSJ article, this one might be helpful.
MFC uses its default OnIdle processing to enable and disable menu items and toolbar buttons, as you can see in the documentation for CWinApp::OnIdle. There doesn't have to be explicit code to enable or disable these items as conditions change, it just happens automatically when nothing else is going on.
Windows itself uses a similar strategy for firing WM_PAINT messages - those only get generated when nothing else is in the message queue.
You use this technique when you have a low-priority task you want to do.

QT Event Problem

I am writing a qt program and have the following requirement.
When 30 sec passed without any click, lock the screen. If someone clicks again after these 30 secs, redirect him to a login screen.
I have read the qt doc about event and I believe that I need either method 1 or 2 to process mouse event.
1.Installing an event filter on qApp
An event filter on qApp monitors all events sent to all objects in the application.
2.Reimplementing QApplication::notify().
Qt's event loop and sendEvent() call this function to dispatch events. By reimplementing it, you get to see events before anybody else.
They also seems powerful to me, but I don't understand their difference.
Which one suits my requirement? Thank You.
You can basically achieve the same thing with either solution except for the fact that QApplication::notify (or its override) will be called before any event filter that may be on your application.
As the first approach does not require subclassing QApplication, it usually is the preferred one.The only reason to override QApplication::notify in your case would be if you needed to override it due to other reasons anyway, e.g. because you need to do anything related to your own custom events.
But looking at your requirements I would personally go for the following solution:
Install an event filter on qApp
Create a timer with a 30 seconds interval
Connect the timer to the lock screen method
Have your event filter reset the timer every time a mouse press is detected.
Dependent on your application you might also want to look for KeyPress events and maybe MouseMove events as well.

Closing a MessageBox automatically

I have a third party encryption library, which may create a MessageBox if key creation fails. The failure can be caused by bad random number generation or other rarities, and in most cases, trying again will result in success. My code will attempt key creation up to three times before deciding it failed.
Now, the issue is that the program may be used with automation. If a MessageBox is created during automation, it will block the process forever, because there's nobody to click the 'OK' button.
Does anyone know of a way to catch when this message box is created and automatically close it?
Anything is fair game, as long as it's not something that will make security suites angry. This means no hooking or code tunneling.
In summary, I need to catch when a MessageBox is created and close it. The MessageBox's creation is outside of my control. Modifying the code at runtime is not acceptable.
Also, I've noticed there are some other similar questions, but they don't have the same requirements.
EDIT: Additional note, I can find the message box via searching through all windows until I find one with a matching title and then send it a WM_CLOSE message, but I don't think this is a great solution. I also have no guarantee that the message box has been/will be displayed, or how long after my call it will be displayed. It could display instantly, it could display 1200 ms later, or it could not display at all.
Just before you begin the encryption process, install a WH_CBT hook, and in its callback watch for an nCode of HCBT_CREATEWND. If you get a matching class name ('#32770 (Dialog)' ?) and a matching title either return a nonzero value from the callback, or if that doesn't work post a WM_CLOSE (or a BM_CLICK to a relevant button if selecting an option is necessary). Uninstall the hook after the process for not messing with every possible dialog your application pops up.
That sounds like bad design on the part of that library. Generally any sort of utility library (like encryption) has no business invoking any kind of GUI (unless you explicitly ask it to).
Is there possibly some configuration or setting in this library that could disable its use of message boxes?
If not, I'd suggest that you might want to investigate using a different library. After all, if the designers of this library have already made this kind of poor design decision once, then there may be other unfortunate surprises lurking in there.
You can hope that it will be found by GetForegroundWindow, but this may catch other applications. The more brute force way is to iterate over all windows with EnumWindows looking for something that has a caption or text equal to this shown by the library.
I have once "remote controlled" an application by sending mouse click events to some controls. I guess you would have to do this in a separate thread that is watching for Events if a window is opened. Pretty ugly but working...
Create a new thread. If your function fails and a Message Box is opened, obtain a handle to the message box by looping through the windows (GetTopWindow, GetNextWindow) and comparing the window's process id to the one returned from GetCurrentProcessId().
Or, you can avoid all the hard work and just hook the MessageBox API with detours. It's not very hard, and if you don't want to pay for detours, you can do it manually.
Call VirtualProtect and set the memory protection at MessageBox at PAGE_EXECUTE_READWRITE
Create a naked function, and use it as a trampoline.
Create a function identical in parameters to MessageBox (this will be your hook)
Create a jump from MessageBox to your hook function.

KeyboardProc returning TRUE causes performance drops

I'm developing an interface for an add-on to a game. I can't use the game API (for several reasons including the fact that the code must be game-agnostic) and I need to get keyboard input from the user so I've decided to use a keyboard hook (WH_KEYBOARD) to process user input when certain conditions are met.
The problem is that while I can receive and process the input correctly, when my hook returns TRUE instead of CallNextHookEx the system seems to take up a lot of time (well over 800ms) before letting things go on as expected and that's not acceptable because it doesn't even allow for a fluid typing experience.
What I have to achieve is preventing the key press message to reach the WndProc, so the question is: what can I do to achieve my target without hurting the game performance so much that the result will be unacceptable?
EDIT: due to specific requirements (games using anticheats which might create problems with my code despite it's not cheating-related) subclassing the active wndproc is not an option.
First you need your DLL to be injected into the target process, either by hooks, or by any other way.
Find the window handle of interest.
Obtain the current window procedure of that window, by calling GetWindowLongPtr(wnd, GWLP_WNDPROC), and save it.
Sub-class the window, by calling SetWindowLongPtr( wnd, GWLP_WNDPROC, &NewWndProc ) where NewWndProc is your DLL-implemented message procedure.
Inside NewWndProc you'll want to process keyboard messages (there're a dozen of them, type "keyboard input" in MSDN index, I can't post more then 1 link). For the rest of windows messages call the original window procedure you've saved during (3), and return the value it returned. Don't call it directly, use CallWindowProc instead.
This way is not very reliable, some antivirus and anti-bot (e.g. "warden client") software might not like it, and debugging may be challenging.
However it should work.
A keyboard hook should not make things that slow. There's probably something else going on that causes the 800ms delay. Is it still slow if your hook does nothing and simply returns TRUE?
If you want to prevent from message to arrive to the WndProc then you need to subclass using SetWindowLong, this way you will be able to catch all messages and decide if to continue their route.
As much as I don't like answering my own question I've found the cause of the delay. The message pump of the games I've tested my code against was implemented with a while(PeekMessage) { GetMessage... } and removing the keyboard input message somehow caused GetMessage to block for sometime. Using PostMessage and WM_NULL helped preventing GetMessage from blocking.

Event handler in Qt with multithread

Does any one know how the event handler manages the posted events?
In my app i have two threads (guiThread and computationThread). After an exception is thrown I call postEvent(..) to an existing dialog. The Qt-Event-Handler holds this one back until the dialog is closed.
Sorry my question is a bit cloudy. I will write it more exactly, if I have time left. I found a work around. But for me the problem is still interesting.
As mentionned in the Qt documentation about QCoreApplication::postEvent :
When control returns to the main event loop, all events that are stored in the queue will be sent using the notify() function.
...which explains why the Qt Event Handler holds the event until the dialog is closed.
If I understand correctly what you want to do, I would try using sendEvent.
I'm guessing that the dialog you created is modal, which would mean that it is running its own event loop. No events posted to the general guiThread will be processed until all modal event loops are exited.
Alternately, if you need the dialog to both be modal and know about the event, you could post the event directly to the dialog. You'll need to figure out how to handle pointers in a shared manner, but if nothing complicated is going on, you might be able to use the QApplication::activeWindow() function.
As others already wrote, I believe this behavior is caused by the fact that the dialog starts its own event loop.
If you use Qt4, you can try using queued signal/slot connections as an alternative to posting events.