Capturing keyboard input and the consequences of hooks - c++

I am writing a VoIP program and one of the standard features is press-to-talk, meaning while holding down a key you record and send audio. The key will react no matter if you are in a videogame or has focus on another window.
My questions;
do all VoIP programs explicitly use keyboard hooks to achieve this? For example, ventrilo/teamspeak/skype/mumble
I have heard keyboard hooks incur a peformance hit on the system since every keyboard message is sent to the VoIP application too. Is there a way to reduce the cost, and how big is the performance hit? My number one priority in my application is performance and effective, low use of computer resources.
Thanks in advance

Is there a way to reduce the cost, and how big is the performance hit?
The performance hit and cost are directly proportional to the amount of work your handler code does.
If you read the documentation it says that these are some of the reasons to do so (emphasis mine):
Monitor messages for debugging purposes
Provide support for recording and playback of macros
Provide support for a help key (F1)
Simulate mouse and keyboard input
Implement a computer-based training (CBT) application

I don't know what other programs use.
Use it and see if there is a performance problem. You're probably pre-optimizing at this point. I've seen it used in Windows apps on Pentium I hardware with no noticeable impact.

Related

Shutting down fan c++ [duplicate]

Is there a Windows standard way to do things such as "start fan", "decrease speed" or the like, from C/C++?
I have a suspicion it might be ACPI, but I am a frail mortal and cannot read that kind of documentation.
Edit: e.g. Windows 7 lets you select in your power plan options such as "passive cooling" (only when things get hot?) vs. "active cooling" (keep the CPU proactively cool?). It seems the OS does have a way to control the fan generically.
I am at the moment working on a project that, among other things, controls the computer fans. Basically, the fans are controlled by the superIO chip of your computer. We access the chip directly using port-mapped IO, and from there we can get to the logical fan device. Using port-mapped IO requires the code to run in kernel mode, but windows does not supply any drivers for generic port IO (with good reason, since it is a very powerful tool), so we wrote our own driver, and used that.
If you want to go down this route, you basically need knowledge in two areas: driver development and how to access and interpret superIO chip information. When we started the project, we didn't know anything in either of these areas, so it has been learning by browsing, reading and finally doing. To gain the knowledge, we have been especially helped by looking at these links:
The WDK, which is the Windows Driver Kit. You need this to compile any driver you write for windows, With it comes a whole lot of source code for example drivers, including a driver for general port-mapped IO, called portio.
WinIO has source code for a driver in C, a dll in C that programmatically installs and loads that driver, and some C# code for a GUI, that loads the dll and reads/writes to the ports. The driver is very similar to the one in portio.
lm-sensors is a linux project, that, among other things, detects your superIO chip. /prog/detect/sensors-detect is the perl program, that does the detecting, and we have spent some time going through the code to see how to interface with a superIO chip.
When we were going through the lm-sensors code, it was very nice to have tools like RapidDriver and RW-everything, since they allowed us to simulate a run of sensors-detect. The latter is the more powerful, and is very helpful in visualising the IO space, while the former provides easier access to some operations which map better to the ones in sensors-detect (read/write byte to port)
Finally, you need to find the datasheet of your superIO chip. From the examples, that I have seen, the environment controllers of each chip provide similar functionality (r/w fan speed, read temperature, read chip voltage), but vary in what registers you have to write to in order to get to this functionality. This place has had all the datasheets, we have needed so far.
If you want something real quick to just lower fans to a level where you know things won't overheat, there's the speedfan program to do so. Figuring out how to configure it in the early versions to automatically lower fans to 50% on computer startup was so painful that my first approach was to simply byte-patch it to start the only superio managed fan I had at lower speed. The newer versions are still bit tough but it's doable - there's a graphical slider system that looks like audio equalizer except that the x axis is temp and y is fan speed. You drag them down one by one. After you figure out how to get manual control for the fan you want, this is next step.
There's a project to monitor hardware (like fans) with C#:
http://code.google.com/p/open-hardware-monitor/
I haven't extensively looked at it, but the source code and use of WinRing0.sys atleast gives the impression that if you know what fan controller you have and have the datasheet, it should be modifiable to also set values instead of just getting them. I don't know what tool is suited (beside kernel debugger) to look at what Speedfan does, if you preferred to snoop around and imitate speedfan instead of looking at the datasheets and trying things out.
Yes, It would be ACPI, and to my knowledge windows doesn't give much/any control over that from user space. So you'd have to start mucking with drivers, which is nigh impossible on windows.
That said, google reveals there are a few open source windows libraries for this for specific hardware... so depending on your hardware you might be able to find something.
ACPI may or may not allow you to adjust the fan settings. Some BIOS implementations may not allow that control though -- they may force control depending on the BIOS/CMOS settings. One might be hard-pressed for a good use case where the BIOS control (even customized) is insufficient. I have come across situations where the BIOS control indeed was insufficient, but not for all possible motherboard platforms.
WIndows Management Instrumentation library (WMI) does provide a Win32_Fan Class and even a SetSpeed method. Alas, the docs say this is not implemented, so I guess it's not very helpful. But you may be able to control things by setting the power state.

Application GUI development platform

Coming from C++ & MFC background, is there any better (maintainability/customization) platform in developing application GUI ?
We are developing industrial applications (machine vision), where :
-Performance-critical (mostly image processing in CPU atm, but GPU is up next)
-Low level hardware interfacing (inhouse PCI device, frame grabber, motion card)
-Real-time data visualization (images / statistical graph)
-Future roadmap includes networkability for distributed processing and remote access.
Cross-platform will not be important for us since the system runs in controlled-environment (customer only cares whether the system runs and they got their output).
There are also concerns on migration cost (3rd party dependencies, training cost for developers and service personnel)
Edit
Clarification on the "image processing" mentioned above:
I'm referring to "picture" (2D information in matrix format) rather than graphic (commonly 3D vectorized). Currently we uses 3rd party imaging library (for spatial domain processing like segmentation, OCR/OCV, morphology, pattern match) and incorporate our result logic.
If you need performance-critical graphics processing, then C++/DirectX or C++/OpenGL are your best bets, hands down. C++/DirectX is arguably the more maintainable of the two.
That said... depending on the actual processing you're doing, you might consider moving portions of your UI to a more maintainable platform. The .NET framework / WPF can do some pretty amazing things, and with good implementation of patterns like MVVM and can be amazingly maintainable. Ditto the networking side; WCF abstracts a lot of common protocols away from the code, making for cleaner, more maintainable networking code. You can even write your translation layer between your unmanaged processing and your managed layer in C++/CLI.
That said, it's all very subjective. I can't tell enough from your bullet points to make a good judgement on whether or not you can offload some or even all of your processing to .NET/C#. It's worth considering, but my gut tells me that it's probably not your best bet.
As a fan of Qt I would be remiss not to mention it.
Although cross-platform is not one of your criteria, it is a nice bonus.
Qt also has good video hardware support through OpenGL (I'm not sure that it will help with capture hardware though).
It is open-source so you can get your hands as dirty as you like.
It is highly customizable.
It is actively developed and has a large community.
MFC programmers should not have much trouble coming up to speed.
You should also read through some of these questions and answers:
Good C++ GUI library for Windows
https://stackoverflow.com/questions/610/gui-programming-apis
What I had did before when developing a C++ scientific application is that, it will develop it completely under console based application. The console based application will able accept various type of command from user keyboard, and perform action accordingly. For example :
image_processor > load input.png
image_processor > save out.png
The good thing on this is, I can 100% in concentrating my algorithm design, without worry much on how to fit into the GUI framework. Either they are MFC or QT.
At the end of day, instead of taking input from keyboard input stream, I will just simply hook my console based application's STDIN, to the GUI application communication channel. My GUI application will then string based command, to talk and receive feedback from the console application.
Guess what I use to develop the GUI? Java Swing :)
I guess I am taking Unix people approach. See what Joel says :
Suppose you take a Unix programmer and a Windows programmer and give them each the task of creating the same end-user application. The Unix programmer will create a command-line or text-driven core and occasionally, as an afterthought, build a GUI which drives that core. This way the main operations of the application will be available to other programmers who can invoke the program on the command line and read the results as text. The Windows programmer will tend to start with a GUI, and occasionally, as an afterthought, add a scripting language which can automate the operation of the GUI interface.
I realize by taking Windows approach, you will end up with a more user friendly application. However, if your main concern is to get the sophisticated algorithm written well and GUI is the secondary, I would suggest that you go for Unix approach.

Qt Application Performance vs. WinAPI/MFC/WTL/

I'm considering writing a new Windows GUI app, where one of the requirements is that the app must be very responsive, quick to load, and have a light memory footprint.
I've used WTL for previous apps I've built with this type of requirement, but as I use .NET all the time in my day job WTL is getting more and more painful to go back to. I'm not interested in using .NET for this app, as I still find the performance of larger .NET UIs lacking, but I am interested in using a better C++ framework for the UI - like Qt.
What I want to be sure of before starting is that I'm not going to regret this on the performance front.
So: Is Qt fast?
I'll try and qualify the question by examples of what I'd like to come close to matching: My current WTL app is Programmer's Notepad. The current version I'm working on weighs in at about 4mb of code for a 32-bit, release compiled version with a single language translation. On a modern fast PC it takes 1-3 seconds to load, which is important as people fire it up often to avoid IDEs etc. The memory footprint is usually 12-20 mb on 64-bit Win7 once you've been editing for a while. You can run the app non-stop, leave it minimized, whatever and it always jumps to attention instantly when you switch to it.
For the sake of argument let's say I want to port my WTL app to Qt for potential future cross-platform support and/or the much easier UI framework. I want to come close to if not match this level of performance with Qt.
Just chiming in with my experience in case you still haven't solved it or anyone else is looking for more experience. I've recently developed a pretty heavy (regular QGraphicsView, OpenGL QGraphicsView, QtSQL database access, ...) application with Qt 4.7 AND I'm also a stickler for performance. That includes startup performance of course, I like my applications to show up nearly instantly, so I spend quite a bit of time on that.
Speed: Fantastic, I have no complaints. My heavy app that needs to instantiate at least 100 widgets on startup alone (granted, a lot of those are QLabels) starts up in a split second (I don't notice any delay between doubleclicking and the window appearing).
Memory: This is the bad part, Qt with many subsystems in my experience does use a noticeable amount of memory. Then again this does count for the many subsystems usage, QtXML, QtOpenGL, QtSQL, QtSVG, you name it, I use it. My current application at startup manages to use about 50 MB but it starts up lightning fast and responds swiftly as well
Ease of programming / API: Qt is an absolute joy to use, from its containers to its widget classes to its modules. All the while making memory management easy (QObject) system and mantaining super performance. I've always written pure win32 before this and I wil never go back. For example, with the QtConcurrent classes I was able to change a method invocation from myMethod(arguments) to QtConcurrent::run(this, MyClass::myMethod, arguments)and with one single line a non-GUI heavy processing method was threaded. With a QFuture and QFutureWatcher I could monitor when the thread had ended (either with signals or just method checking). What ease of use! Very elegant design all around.
So in retrospect: very good performance (including app startup), quite high memory usage if many submodules are used, fantastic API and possibilities, cross-platform
Going native API is the most performant choice by definition - anything other than that is a wrapper around native API.
What exactly do you expect to be the performance bottleneck? Any strict numbers? Honestly, vague ,,very responsive, quick to load, and have a light memory footprint'' sounds like a requirement gathering bug to me. Performance is often overspecified.
To the point:
Qt's signal-slot mechanism is really fast. It's statically typed and translates with MOC to quite simple slot method calls.
Qt offers nice multithreading support, so that you can have responsive GUI in one thread and whatever else in other threads without much hassle. That might work.
Programmer's Notepad is an text editor which uses Scintilla as the text editing core component and WTL as UI library.
JuffEd is a text editor which uses QScintilla as the text editing core component and Qt as UI library.
I have installed the latest versions of Programmer's Notepad and JuffEd and studied the memory footprint of both editors by using Process Explorer.
Empty file:
- juffed.exe Private Bytes: 4,532K Virtual Size: 56,288K
- pn.exe Private Bytes: 6,316K Virtual Size: 57,268K
"wtl\Include\atlctrls.h" (264K, ~10.000 lines, scrolled from beginning to end a few times):
- juffed.exe Private Bytes: 7,964K Virtual Size: 62,640K
- pn.exe Private Bytes: 7,480K Virtual Size: 63,180K
after a select all (Ctrl-A), cut (Ctrl-X) and paste (Ctrl-V)
- juffed.exe Private Bytes: 8,488K Virtual Size: 66,700K
- pn.exe Private Bytes: 8,580K Virtual Size: 63,712K
Note that while scrolling (Pg Down / Pg Up pressed) JuffEd seemed to eat more CPU than Programmer's Notepad.
Combined exe and dll sizes:
- juffed.exe QtXml4.dll QtGui4.dll QtCore4.dll qscintilla2.dll mingwm10.dll libjuff.dll 14Mb
- pn.exe SciLexer.dll msvcr80.dll msvcp80.dll msvcm80.dll libexpat.dll ctagsnavigator.dll pnse.dll 4.77 Mb
The above comparison is not fair because JuffEd was not compiled with Visual Studio 2005, which should generate smaller binaries.
We have been using Qt for multiple years now, developing a good size UI application with various elements in the UI, including a 3D window. Whenever we hit a major slowdown in app performance it is usually our fault (we do a lot of database access) and not the UIs.
They have done a lot of work over the last years to speed up drawing (this is where most of the time is spent). In general unless you really do implement a kind of editor usually there is not a lot of time spent executing code inside the UI. It mostly waits on input from the user.
Qt is a very nice framework, but there is a performance penalty. This has mostly to do with painting. Qt uses its own renderer for painting everything - text, rectangles, you name it... To the underlying window system every Qt application looks like a single window with a big bitmap inside. No nested windows, no nothing. This is good for flicker-free rendering and maximum control over the painting, but this comes at the price of completely forgoing any possibility for hardware acceleration. Hardware acceleration is still noticeable nowadays, e.g. when filling large rectangles in a single color, as is often the case in windowing systems.
That said, Qt is "fast enough" in almost all cases.
I mostly notice slowness when running on a Macbook whose CPU fan is very sensitive and will come to life after only a few seconds of moderate CPU activity. Using the mouse to scroll around in a Qt application loads the CPU a lot more than scrolling around in a native application. The same goes for resizing windows.
As I said, Qt is fast enough but if increased battery draining matters to you, or if you care about very smooth window resizing, then you don't have much choice besides going native.
Since you seem to consider a 3 second application startup "fast", it doesn't sound like you would care at all about Qt's performance, though. I would consider 3 second startup dog-slow, but opinions on that vary naturally.
The overall program performance will of course be up to you, but I don't think that you have to worry about the UI. Thanks to the graphics scene and OpenGL support you can do fast 2D/3D graphics too.
Last but not least, an example from my own experience:
Using Qt on Linux/Embedded XP machine with 128 MB of Ram. Windows uses MFC, Linux uses Qt. Custom user GUI with lots of painting, and a regular admin GUI with controls/widgets. From a user's point of view, Qt is as fast as MFC. Note: it was a full screen program that could not be minimized.
Edited after you have added more info:
you can expect a larger executable size (especially with Qt MinGW) and more memory usage. In your case, try playing with one of the IDEs (e.g. Qt Creator) or text editors written in Qt and see what you think.
I personally would choose Qt as I've never seen any performance hit for using it. That said, you can get a little closer to native with wxWidgets and still have a cross-platform app. You'll never be quite as fast as straight Win32 or MFC (and family) but you gain a multi-platform audience. So the question for you is, is this worth a small trade-off?
My experience is mostly with MFC, and more recently with C#. MFC is pretty close to the bare metal so unless you define a ton of data structure, it should be pretty quick.
For graphics painting, I always find it useful to render to a memory bitmap, and then blt that to the screen. It looks faster, and it may even be faster, because it's not worrying about clipping.
There usually is some kind of performance problem that creeps in, in spite of my trying to avoid it. I use a very simple way to find these problems: just wait until it's being subjectively slow, pause it, and examine the call stack. I do this a number of times - 10 is usually more than enough. It's a poor man's profiler but works well, no fuss, no bother. The problem is always something no one could have guessed, and usually easy to fix. This is why it works.
If there are dialogs of any complexity, I use my own technique, Dynamic Dialogs, because I'm spoiled. They are not for the faint-of-heart, but are very flexible and perform nicely.
I once made an app to determine the "primeness" of a number (whether it was prime or composite).
I first attempted a Qt GUI, and it took 5 hours to return the answer for 1,299,827 on a computer with 8GB of RAM and an AMD 1090T # 4GHz running no other foreground processes under Linux.
My second attempt used a QProcess of a console application that used the exact same code. On a laptop with 1.3GB of RAM and a 1.4GHz CPU, the response came with no perceivable delay.
I will not deny, though, that it is far easier than GTK+ or Win32, and it handles things quite nicely, but separate intensive processing ENTIRELY from the GUI if you use it.

How do I detect desktop transition effects?

I want to minimise my application, take a screenshot of the current desktop and return my application back to its original state.
This has been working fine under windows XP, however under testing on different Vista machines the minimise time of 200 milliseconds is no longer valid.
Is there a way to ask the operating system when it has finished these fancy effects or lookup how long it has been given to perform the operation?
While I don't know of a way to do what you ask, I have a suggestion: instead of minimizing your application's window, why not hide it (with ShowWindow(SW_HIDE))? That will not be subject to the animation effects, so should be pretty much instantaneous.
Maybe instead minimizing you should bring desktop to front?
The closest I can find is SPI_GETUIEFFECTS, which tells you if such effects are enabled at all.
If enabled, you could of course use SPI_SETUIEFFECTS to turn them off. But that's a rather shotgun method - how would you restore them? It's probably better to temporarily turn off the ones that bother you most.

Running background services on a PocketPC

I've recently bought myself a new cellphone, running Windows Mobile 6.1 Professional. And of course I am currently looking into doing some coding for it, on a hobby basis. My plan is to have a service running as a DLL, loaded by Services.exe. This needs to gather som data, and do som processing at regular intervals (every 5-10 minutes).
Since I need to run this at regular intervals, it is a bit of a problem for me, that the system typically goes to sleep (suspend) after a short period of inactivity by the user.
I have been reading all the documentation I could find on MSDN, and MSDN blogs about this subject, and it seems to me, that there are three possible solutions to this problem:
Keep the system in an "Always On"-state, by calling SystemIdleTimerReset periodically. This seems a bit excessive, and is therefore out of the question.
Have the system periodically waken up with CeRunAppAtTime, and enter the unattended state, to do my processing.
Use the unattended state instead of going into a full suspend. This would be transparent to the user, but the system would never go into sleep.
The second approach seems to be preferred, however, this would require an executable to be called by the system on wake up, with the only task of notifying my service that it should commence processing. This seems a bit unnecessary and I would like to avoid this extra executable. I could of course move all my processing into this extra executable, but I would like to use some of the facilities provided when running as a service, and also not have a program pop up (even if its in the background) whenever processing starts.
At first glance, the third approach seems to have the same basic problem as the first. However, I have read on some of the MSDN blogs, that it might be possible to actually conserve battery consumption with this approach, instead of going in and out of suspend mode often (The arguments for this was that the nature of the WM platform is to have a very little battery consumption, when the system is idle. And that going in and out of suspend require quite a bit of processing).
So I guess my questions are as following:
Which approach would you recommend in my situation? With respect to keeping a minimum battery consumption, and a nice clean implementation.
In the case of approach number two, is it possible to eliminate the need for a notifying executable? Either through alternative API functions, or existing generic applications on the platform?
In the case of approach number three, do you know of any information/statistics relevant to the claim, that it is possible to extend the battery lifetime when using unattended mode over going into suspend. E.g. how often do you need to pull the system out of suspend, before unattended mode is to be preferred.
Implementation specific (bonus) question: Is it necessary to regularly call SystemIdleTimerReset to stay in unattended mode?
And finally, if you think I have prematurely eliminated approach number one, please tell me why.
Please include in your response whether you base your response on knowledge, or are merely guessing (the latter is also very welcome!).
Please leave a comment, if you think I need to clarify any parts of this question.
CERunAppAtTime is a much-misunderstood API (largely because of the terrible name). It doesn't have to run an app. It can simply set a named system event (see the description of the pwszAppName parameter in the MSDN docs). If you care to know when it has fired (to lat your app put the device to sleep again when it's done processing) simply have a worker thread that is doing a WaitForSingleObject on that same named event.
Unattended state is often used for devices that need to keep an app running continuously (like an MP3 player) but conserve power by shutting down the backlight (probably the single most power consuming subsystem).
Obviously unattended mode uses significantly more powr than suspend, becasue in suspend the only power draw is for RAM self-refresh. In unattended mode the processor is stuill powered and running (and several peripherals may be too - depends on how the OEM defined their unattended mode).
SystemIdleTimerReset simply prevents the power manager from putting the device into low-power mode due to inactivity. This mode, whether suspended, unattended, flight or other, is defined by the OEM. Use it sparingly because when your do it impacts the power consumption of the device. Doing it in unattended mode is especially problematic from a user perspective because they might think the device is off (it looks that way) but now their battery life has gone south.
I had a whole long post detailing how you shouldn't expect to be able to get acceptable battery life because WM is not designed to support what you're trying to do, but -- you could signal your service on wakeup, do your processing, then use the methods in this post to put the device back to sleep immediately. You should be able to keep the ratio of on-time-to-sleep-time very low this way -- but as you say, I'm only guessing.
See also:
Power-Efficient Apps (MSDN)
Power To The People (Developers 1, Developers 2, Devices)
Power-Efficient WM Apps (blog post)