How to ensure SetWindowsHookEx priority - winapi

I'm using SetWindowsHookEx to hook Keyboard ( idHook = WH_KEYBOARD ). In most case , the customer computers also running an Unicode Typing Software, it also hooking the keyboard with same method. So how i ensure my application run hook with highest priority or lowest priority than other software? (in some case i want my software with higher priority than the Unicode Typer, in some other case i want it run with lower priority)

Hook priorities are based on the order in which the hooks are installed. Newer hooks have higher priority than older hooks. There is no API exposed to query the order of existing hooks, so the only way to know if your hook is higher or lower than other hooks is to detour SetWindowsHookEx() itself in every running process and keep track of which processes are calling it.
The alternative is to stop using SetWindowsHookEx(), at least for high priority hooking. Use the RAW Input API instead. Then you will receive input events directly from the keyboard itself. However, you cannot use RAW Input to block other processes from receiving keyboard input, if that is your goal.

Related

Is it possible to get notified when an opened position has been modified?

May I know how could I get notified in MQL4, if any of my placed or opened positions have been modified, due to getting [stop loss] or [take profit] or a pending order got triggered?
The reason is that I need to perform certain actions when my placed or opened positions are changed.
Yes, it is, Sir.
One may opt to run an MQL4 code, that monitors the state of the set of both the placed and opened orders, as required above, and send you either an email or other message of your choice, whenever a monitored event happens to show up in the MetaTrader Terminal ( the Market events get reported into the Terminal from the Broker side as events ).
So feel free to use this approach to solving the expressed need. It is programmatically doable either using a Script or an ExpertAdvisor MQL4-code-execution functions. Can even go into distributed framework, if not willing to rely on MetaTrader platform constraints and implement just event-signalling and process the event externally, outside of the MQL4-code-base ( in C, C++, java, php, python, go, Erlang etc. depending on your preferences and performance / latency needs ).
In mql5 - OnTradeTransaction() event, in mql4 it is not supported so need to keep everything in memory and loop over the open trades every tick/second/N milliseconds and compare current orders and their types with previous tick orders and notify if something has changed.

GetMessage() while the thread is blocked in SwapBuffers()

Vsync blocks SwapBuffers(), which is what I want. My problem is that, since input messages go to the same thread that owns the window, any messages that come in while SwapBuffers() is blocked won't be processed immediately, but only after the vsync triggers the buffer swap and SwapBuffers() returns. So I have all my compute threads sitting idle instead of processing the scene for rendering in the next frame using the most recent input. I'm particularly concerned with having very low latency. I need some way to access all pending input messages to the window from other threads.
Windows API provides a way to wait for either Windows events or input messages using MsgWaitForMultipleObjects(), yet there's no similar way to wait for a buffer swap together with other things. That's very unfortunate.
I considered calling SwapBuffers() in another thread, but that requires glFinish() to be called in the window's thread before signalling another thread to SwapBuffers(), and glFinish() is still a blocking call so it's not a good solution.
I considered hooking, but that also looks like a dead end. Hooking with WH_GETMESSAGE will have the GetMsgProc() be called not asynchronously, but when the window's thread calls GetMessage()/PeekMessage(), so it's no help. Installing a global hook doesn't help me either due to the need of calling RegisterTouchWindow() with a specific window handle to process WM_TOUCH -- and my input is touch. And, while for mouse and keyboard, you can install low level hooks that capture messages as they're posted to the thread's queue, rather than when the thread calls GetMessage()/PeekMessage(), there appears to be no similar option for touch.
I also looked at wglDelayBeforeSwapNV(), but I don't see what's preventing the OS from preempting a thread sometimes after the call to that function but before SwapBuffers(), causing a miss of the next vsync signal.
So what's a good workaround? Can I make a second, invisible window, that will somehow be always the active one and so get all input messages, while the visible one is displaying the rendering? According to another discussion, message-only windows (CreateWindow with HWND_MESSAGE) are not compatible with WM_TOUCH. Is there perhaps some undocumented event that SwapBuffers() is internally waiting on that I could access and feed to MsgWaitForMultipleObjects()? My target is a fixed platform (Windows 8.1 64-bit) so I'm fine with using undocumented functionality, should it exist. I do want to avoid writing my own touchscreen driver, however.
Out of curiosity, why not implement your entire drawing logic in that other thread? It appears the problem you are running into is that the message pump is driven by the same thread that draws. Since Windows does not let you drive the message pump from a different thread than the one that created the window, the easiest solution would just be to push all the GL stuff into a different thread.
SwapBuffers (...) is also not necessarily going to block. As-per requirements of VSYNC an implementation need only block the next command that would modify the backbuffer while all backbuffers are pending a swap. Triple buffering changes things up a little bit by introducing a second backbuffer.
One possible implementation of triple buffering will discard the oldest backbuffer when it comes time to swap, thus SwapBuffers (...) would never cause blocking (this is effectively how modern versions of Windows work in windowed mode with the DWM enabled). Other implementations will eventually present both backbuffers, this reduces (but does not eliminate) blocking but also results in the display of late frames.
Unfortunately WGL does not let you request the number of backbuffers in a swap-chain (beyond 0 single-buffered or 1 double-buffered); the only way to get triple buffering on Windows is using driver settings. Lowest message latency will come from driving GL in a different thread, but triple buffering can help a little bit while requiring no effort on your part.

How does powercfg -energy detect the requested timer resolution

How does "powercfg -energy" command detect the requested timer resolution of each individual program running at the time?
I imagine one way would be injecting into each of running processes and inside that process calling timeEndPeriod for each increased resolution (values 1-15) in a loop over these resolutions and checking whether the timeEndPeriod call for a current resolution returns TIMERR_NOCANDO or TIMERR_NOERROR (note: these return values are NOT correspondingly false and true). And if it returns TIMERR_NOERROR then concluding that the program is using that frequency, and then calling again timeBeginPeriod. But this method seems cumbersome. Moreover, it is a bit intrusive since it modifies the state of the process, and also assumes that powercfg is able to inject into all processes.
Is there instead some documented or undocumented system API that enables requesting that information for foreign processes? At least I would like to know how it works, even if that API remains a secret...
A related (but not the main) question is, how to get the maximum timer resolution (minimum interval) that is currently in effect in the system in case I am not interested in the requests of individual applications? I imagine that maybe GetSystemTimeAdjustment()'s lpTimeIncrement helps with that, but I am not too sure. Please confirm me or propose an alternate method.
You may use the undocumented API of NtQueryTimerResolution().
NTSTATUS NtQueryTimerResolution(OUT PULONGMinimumResolution,
OUT LONGMaximumResolution,
OUT PULONGActualResolution);
See this post for an example on how to use it. But it will only give the ActualResolution as configured by any process. It does not give the information which process has configured which multimedia timer resolution.
You wouldn't want to change each processes mutimedia setting to find out which process has aquired which resolution. It would only be needed to obtain information on which process has requested ActualResolution.
Note: powercfg /energy is only available from Windows 7 / Windows Server 2008 R2 upwards.

Can abusing RegisterWindowMessage lead to resource exhaustion?

MSDN advises that RegisterWindowMessage() function is only used for registering messages to be sent between the processes. If a message is needed for sending within one process it can be safely selected from the range WM_APP through 0xBFFF.
However in our codebase I often see that RegisterWindowMessage() is used for messages only sent within one process. I suppose that this was done because of perceived simplicity of using RegisterWindowMessage() since it doesn't require manually distributing the message identifiers in the WM_APP..0xBFFF range.
Do I understand correctly that if many applications are run on one machine and they all call RegisterWindowMessage() with different strings they could exhaust the range of message identifiers allowed to return by RegisterWindowMessage() and for some of them it will just return a value indicating a failure? What could be a valid reason for using RegisterWindowMessage() messages in cases where WM_APP..0xBFFF range messages would suffice?
IMHO there is no valid reason to use RegisterWindowMessage if you are only sending messages to yourself
There is no (documented) way to un-register a message, so after your app quits, that registered message will stay in the atom table until reboot/logoff (I can't remember exactly where this atom table is stored, the window station or terminal server session instance probably)
The reason you need to use RegisterWindowMessage even when messaging to yourself is that it protects you from the idiot who broadcasts messages in the WM_APP + N range.
Yes, this does happen.
Abusing RegisterWindowMessage can potentially make a windows box unusuable. This is especially true if the window message names are dynamically generated and a bug causes out of control windows message allocation. In this case the global atom table in your windows station/ desktop will fill up and any process using User32.dll (basically, any app) will fail to start, create windows, etc.
There is a bug out there in Delphi / Borland products that registers messages that start with ControlOfsXXXXXX where XXXX is a memory address (or other dynamic modifier). Apps that are started and stopped frequently will register multiple ControlOfsXXXX atoms and eventually exhaust atom space. For more details see:
http://blogs.msdn.com/b/ntdebugging/archive/2012/01/31/identifying-global-atom-table-leaks.aspx
And
https://forums.embarcadero.com/thread.jspa?threadID=47678
A possible advantage is that Spy++ can display more informative text, therefore debugging is a bit easier. Compare
<00058> 00330CA2 S message:0x0419 [User-defined:WM_USER+25] wParam:00000000 lParam:00000000
with
<00129> 004F0DA0 S message:0xC2B0 [Registered:"AFX_WM_ONCHANGE_ACTIVE_TAB"] wParam:00000001 lParam:02B596E8
Of course, in principle there is a chance to run out of message IDs. On the other hand, in the source code of the MFC Feature Pack there are 52 calls to RegisterWindowMessage. So there are still 16300 IDs left for other applications.

How to deal with a second event-loop with message-dispatch?

I am working on a program which is essentially single-threaded, and its only thread is the main event-loop thread. Consequently, all its data structures are basically not protected by anything like critical region.
Things work fine until it recently integrates some new functions based on DirectShow API. Some DirectShow APIs open a second event-loop and within that second loop it dispatch messages (i.e. invoke other event-handling callbacks unpredictably). So when a second event-handling function is invoked, it might damage the data struct which is being accessed by the function that invokes the DirectShow API.
I have some experience in kernel programming. And what comes in my mind is that, for a single-threaded program, how it should deal with its data structure is very like how kernel should deal with per-CPU data structure. And in kernel, when a function accesses per-CPU data, it must disable the interrupt (very like the message-dispatching in a second event-loop). However, I find there is no easy way to either avoid invoke DirectShow API or to prevent the create of a second event-loop within them, is there any way?
mutexes. semaphores. locking. whatever name you want to call it, that's what you need.
There are several possible solutions that come to mind, depending on exactly what's going wrong and your code:
Make sure your data structures are in a consistent state before calling any APIs that run a modal loop.
If that's not possible, you can use a simple boolean variable to protect the structure. If it's set, then simply abort any attempt to update it or queue the update for later. Another option is to abort the previous operation.
If the problem is user generated events, then disable the problematic menus or buttons while the operation is in progress. Alternatively, you could display a modal dialog.

Resources