Creating a 'shutting down' window for a closing application - c++

I am relatively new to C++ programming and currently using Visual Studio 2012 API. My OS is Windows 7 64-bit. I would like to write a program in C++ which displays a message box or window with a simple shutdown message e.g. 'shutting down.....' or something similar when I close a specific application. This window I am hoping will appear for the duration of the app exit time and then close.
Is it possible to create a handle which will retrieve the exit time for a running application when it is abruptly closed? And if so, how could I use this exit time in a statement which will display the message box?
I would appreciate constructive criticism as I am new to this language. Thank you sincerely for any advice you impart. If requested, I will display all source code.
I don't think this is the right way to go about this but anyway, below is a snippet of the code which I have been toying with, as part of a greater VS Win32 application project:
LPTSTR lpchText(_T("Shutting down...."));
LPFILETIME lpExitTime = 0; //Initialise
TCHAR Buffer[_MAX_PATH];
DWORD size = _MAX_PATH;
LPCTSTR lpStr(_T("C:\Program Files\Common Files\ExampleApp.exe")); // Path to executable app.
AssocQueryString( ASSOCF_OPEN_BYEXENAME,
ASSOCSTR_EXECUTABLE,
lpStr,
NULL,
Buffer,
&size
);
GetProcessTimes(
AssocQueryString,
NULL,
lpExitTime,
NULL,
NULL
);
while(lpExitTime){
MessageBoxEx(
_In_opt_ hWnd,
_In_opt_ lpchText,
_In_opt_ lpCaption,
_In_opt_ MB_ICONEXCLAMATION
,0
);
};
return TRUE;
enter code here

I guess shutting down the application is a lengthy operation othervise a normal application will be closed so fast that the user will have no chance to actual see the window.
But of course it possible, in meta code this is the steps.
Attach to the running process. You can enumrate the running process from the name of the executable to find the correct process.
Once you have the handle to the process you can attach to the process message loop.
Listen for the WM_QUIT (assuming it is a Windows applictaion) message and then display the window.
Wait for the process handle using MsgWaitForMultipleObject, the function will signal when the process terminates.
Attaching to other processes has some security issues so it might not work for a regular user.
Other options to explore is to handle it in a power Shell script or make a small launcher application that in turn starts the actual application.
Is it an option to modify the application itself to have this functionality?

Related

Hook procedure for Journal Record Hook never being called

I'm trying to create a simple application to record and playback a series of keyboard and mouse commands (macros). Read the documentation and concluded that the most suitable implementation (if not the only one) would be to set a Windows journal record hook (WH_JOURNALRECORD) and play it back with a journal playback one (WH_JOURNAL_PLAYBACK).
According to the documentation, these hooks don't need to reside in a DLL, instead they can be in an executable (application). So, I had the Visual Studio creating a simple Win32 application for me. It's a very classic application, registering a window class, creating the window, and running a message-loop. The documentation also mentions that the hook procedures for WH_JOURNALRECORD/WH_JOURNAL_PLAYBACK hooks run in the context of the thread that set them. However, it doesn't specifically mention what this thread should be doing, eg run a message-loop, sleep in an alertable state or what. So I just set the hook and run the message loop - it's the application's main and only thread. It's what some code samples I found also do, albeit they don't seem to work as of now, as they are quite old, and some Windows security updates have made things quite more difficult.
I believe I have taken all the necessary steps I have found in some samples and posts:
Set the Manifest options "UAC Execution Level" to "requireAdministrator (/level='requireAdministrator')" and "UAC Bypass UI Protection" to "Yes (/uiAccess='true')".
Created and installed a certificate - the application is signed with it after built.
The executable is copied to System32 (trusted folder) and run from there "As Administator".
Without the above actions, installation of the hook fails, with an error-code of 5 (Access denied).
I have managed to successfully (?) install the WH_JOURNALRECORD hook (SetWindowsHookEx() returns a non-zero handle), however the hook procedure is not called.
Below is my code (I have omitted the window class registration, window creation, window procedure and About dialog stuff, as there is nothing interesting or special in there - they do just the barebones):
// Not sure if these are needed, found it in some code samples
#pragma comment(linker, "/SECTION:.SHARED,RWS")
#pragma data_seg(".SHARED")
HHOOK hhJournal = NULL;
#pragma data_seg()
// Not sure if the Journal proc needs to be exported
__declspec(dllexport) LRESULT CALLBACK _JournalRProc(_In_ int code, _In_ WPARAM wParam, _In_ LPARAM lParam)
{
Beep(1000, 30); // Clumsy way to trace the JournalRProc calls
return CallNextHookEx(NULL, code, wParam, lParam);
}
void AddKMHooks(HMODULE _hMod)
{
if (hhJournal) return;
MessageBox(NULL, "Adding Hooks", szTitle, MB_OK | MB_ICONINFORMATION | MB_TASKMODAL);
hhJournal = SetWindowsHookEx(WH_JOURNALRECORD, _JournalRProc, _hMod, 0);
if (!hhJournal)
{
CHAR s[100];
wsprintf(s, "Record Journal Hook Failed!\nThe Error-Code was %d", GetLastError());
MessageBox(NULL, s, szTitle, MB_OK | MB_ICONSTOP | MB_TASKMODAL);
}
}
void RemoveKMHooks()
{
if (!hhJournal) return;
MessageBox(NULL, "Removing Hooks", szTitle, MB_OK | MB_ICONINFORMATION | MB_TASKMODAL);
UnhookWindowsHookEx(hhJournal);
hhJournal = NULL;
}
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here.
// Initialize global strings
LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDC_KMRECORD, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance(hInstance, nCmdShow)) return FALSE;
HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_KMRECORD));
AddKMHooks(hInstance);
// Calling AddKMHooks(GetModuleHandle(NULL)) instead, delivers the same results
MSG msg;
// Main message loop:
while (GetMessage(&msg, nullptr, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
// Once the hook has is set the GetMessage() call above
// always returns a WM_TIMER message with a timer ID of 1,
// posted to the queue with the PostMessage() function,
// as the Spy++ tool reports
RemoveKMHooks();
return (int) msg.wParam;
}
I monitored the application with the Spy++ tool, and found that when the hook is set, the application receives a series of successive WM_TIMER timer messages, with a timer ID of 1, posted to the queue with the PostMessage() function (P in Spy++). The window handle for these messages is reported to belong to the same application and thread as the main window, and its class name is "UserAdapterWindowClass". My code neither creates timers nor explicitly creates any window of this class, so apparently these are created by the system. Also, there is another message, with an ID of 0x0060 (Unknown!), posted to the same window only once, after the 1st or 2nd WM_TIMER one.
The application appears to somehow "lock" the system (recording, waiting for a resource, or what?), until I press Alt+Ctrl+Del, which the documentation says stops recording (I have not yet implemented some mechanism to stop recording/uninstall the hook at will, so this is what I use so far). The hook procedure seems to never be called, and this is the problem I'm facing at this point. I have considered examining the code parameter in the hook procedure and act accordingly, but I'm not even close to this, as the procedure is never called - and therefore it would have no effect - so I just call CallNextHookEx() in there (and assume it would work well).
Notes:
The hook procedure may occasionally be called just once, but it's rather rare (almost non-reproducible) and definitely not consistent, so I think I can't rely on this; the code parameter is 0 (HC_ACTION). Tested it though, and returning either zero or non-zero, either calling CallNextHookEx() or not, makes no difference at all.
I have also tried to set the hook in another thread (created after the main one has started processing messages), which then as well runs a message-loop, but I get exactly the same behavior.
Could someone please explain what may be wrong here? Checked some other posts too, esp these ones: SetWindowsHookEx for WH_JOURNALRECORD fails under Vista/Windows 7 and WH_JOURNALRECORD hook in Windows (C++) - Callback never called. , however couldn't find a solution, and I have to note that the usage conditions differ too. What I'm experiencing is closest to this SetWindowsHookEx(WH_JOURNALRECORD, ..) sometimes hang the system though in my case this happens always, not just "sometimes".
I would greatly appreciate any help.
I have uploaded the solution (sources + VS files, but not the .exe, .obj., .pch, .pdb etc file, so a rebuild is required) here, if anyone would like to take a look.
Thank you in advance
EDIT:
Tested the application under different configurations.
Initially, the application was created in Visual Studio 2017, and tested under a Windows 10 Pro 32-bit version 1803, 2-core AMD processor computer (VS2017 is installed on this machine). Got the results described above.
Then tested under a Windows 10 Pro 64-bit version 1903, 4-core AMD processor computer. This machine had a very old version of Visual Studio installed (although it was not involved in development and testing in any way). Installed the certificate and run the application (both created on the other machine). Initially the result was the same (hook proc never called).
Tried deleting the certificate from the "PrivateCertStore" store location, leaving only the copy under "Trusted Root Certification Authorities" (this is the way the batch file I wrote, calling makecert and certmgr, stores the certificate, ie under both the above locations). Unexpected, but it worked, got multiple beeps as I moved the mouse! Tested it again, adding/removing/moving the certificate and the behaviour was fully reproducible: the certificate needed to be installed under "Trusted Root Certification Authorities" only, for the hook to work.
Then repeated the above test on the 32-bit machine. It didn't work there, the application was "frozen" as before (getting only WM_TIMER messages).
On the 64-bit machine, uninstalled the old VS version and quite a few Windows SDK versions installed there, and installed VS 2019 Community Edition. Rebuilt the application in VS2019 (created and installed the certificate anew, and signed the executable). The application now does not work under either machine (again, hook creation succeeds, but the hook proc is not called). Maybe the VS2019 installation, or some Windows Update has caused this.
Identically, the application/certificate created on the 32-bit machine does not work under either machine now.
So it must be a Windows module or some requirements about the certificates which I don't meet, that cause this. Seacrhed on the internet a lot, but can't find which specs the certificate must conform to. For example, what are the requirement about the format, private key or the purposes (now I have all purposes checked, altough I also tried checking only Code Signing, which made no differnce). The makecert utility is now deprecated (the documentation suggests creating certificates with PowerShell instead) but I don't know if this is somehow related to my problem.
I have only come to two conclusions:
- The certificate must be installed under "PrivateCertStore", for the application to be possible to be built (otherwise signing fails). Possibly because I have the /s PrivateCertStore option set in my script. But,
- The certificate must be installed under "Trusted Root Certification Authorities", for the application to be able to be run (otherwise execution fails, with an access-denied error).

How to create desktop icon / button to start users Windows screensaver with options set

I need a button I can put on the users desktop/process bar in Windows 8 (any sub menu is unacceptable), that will start the users screensaver (with password protection, custom parameters etc). This can for example be a shortcut to a batch script.
Some suggestions for solutions I have found:
Starting screensaver from /system32: Does not work
Starts a specific screensaver you choose, not the users screensaver.
Does not take parameters (ie wrong text/pic and no password protection).
WIN + L: Does not work.
It is not a button on the users Desktop, and SendKeys does not seem to be able to do the WIN key, so a batch script for this is not possible.
It goes to log in screen, not screensaver.
rundll32.exe user32.dll, LockWorkStation: Does not work.
It corrupts the stack - https://blogs.msdn.microsoft.com/oldnewthing/20040115-00/?p=41043/
C++ program: So far this is what I have that might work.
#include <windows.h>
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int cmdShow)
{
HWND DeskWin = GetDesktopWindow();
Sleep(750);
PostMessage(DeskWin, WM_SYSCOMMAND, SC_SCREENSAVE, NULL);
return 0;
}
I have never worked with Windows system messages before, so any comments / thoughts on if this will always work is appreciated.
Or if someone just have a way they think is better.
--
Reasons for the need: IT-scared users. They will laugh at you if you suggest remembering a hotkey combination, or going through multiple menus (like Start -> userName -> Lock), the latter is also a time problem as they might have to leave computer fast (hence the need for password protection).
EDIT** C++ Code has been modified to reflect feedback. Sendmessage changed to Postmessage, don't want a blocking call in a codesnip like this (but don't see why it should be thrown at DefWindowProc when the window is known). Symbolic names found (http://wiki.winehq.org/List_Of_Windows_Messages , can't post more links, MSDN has the second parameters under WM_SYSCOMMAND), WinMain is a Visual Studio thing to avoid the console pop up, which some people find alarming.
There is no built-in batch command for running the user's screensaver (without using a 3rd party solution to facilitate it). The code you have come up with is the correct solution for starting the user's screen saver. However, don't use magic number literals like you have shown. There are defines available for those values, use them:
#include <windows.h>
int main(void)
{
SendMessage(GetDesktopWindow(), WM_SYSCOMMAND, SC_SCREENSAVE, 0);
return 0;
}
Compile your code into an .exe file, install it on the user's PC somewhere, and create a shortcut to it on the user's Desktop.

How do I keep my screenshot-making console program from blocking the screenshot?

I have code to make a screenshot, but here is what my program produces:
screenshot with control program blocking some of the screen http://imageshack.us/a/img27/7387/71240043.png
My program's console pops up and gets in the way. This is a split-second pop-up as the program takes the screen shot the split-second you double-click it.
I did some searching for information for how to hide it, and found a forum with the following recommendation:
change the application type from "console" to "GUI application" in the target options (project properties -> tab "build targets").
But setting it to GUI application didn't get rid of the split-second console.
I tried looking for code to hide the console with, and found an example:
HWND hWnd = GetConsoleWindow();
ShowWindow( hWnd, SW_HIDE );
However, writing code to hide the console still has the console pop up and block the screenshot in the split second it appears.
What can I do to stop the console from appearing in that split second? I'm not bothered if the console is simply minimised, so long as it doesn't block the shot.
I don't think just switching the type is enough, since you need to change the entry point form main to WinMain too. Look at this example of how to make a windowless application ( http://social.msdn.microsoft.com/Forums/en/vcgeneral/thread/82f506c4-ac1f-48c1-a5dc-51bfe99cf850 ), I'd suggest making a new Win32 project and then copying over the code you have.
Hacky, but... after hiding the window you can delay long enough for that to take effect on-screen. Here I use C++11 (#include <thread> for this_thread and #include <chrono> for milliseconds) so you'd need to use VS2012 to use this exact code to delay.
HWND console = GetConsoleWindow();
if (!console)
; // handle error
BOOL was_visible = ShowWindow(console, SW_HIDE);
// delay for a fraction of a second...
std::this_thread::sleep_for(std::chrono::milliseconds(100));
// ... take screen shot
if (was_visible)
ShowWindow(console, SW_SHOW);
Using Rudolf's suggestion, I did the research and can answer the question specifically:
Change int main() to int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd). (Correction) This will only work if the settings are graphical.
And to deal with the issue of not having access to int main's argc/argv options, use __argc and __argv, which is an external variable found in stdlib.h.
See also http://support.microsoft.com/kb/126571

How do you create a Message Box thread?

I have tried doing things like...
const char *MessageBoxText = "";
DWORD WINAPI CreateMessageBox(LPVOID lpParam){
MessageBox(NULL, MessageBoxText, "", MB_OK|MB_APPLMODAL);
return TRUE;
}
MessageBoxText = "Blah, Blah, Blah...";
CreateThread(NULL, 0, &CreateMessageBox, NULL, 0, NULL);
However, this does not seem to work correctly for the task I am trying to perform.
What is the best way to create a thread for a message box, without having it glitch up?
Consider passing message text as thread parameter instead of global variable, to make code thread-safe.
DWORD WINAPI CreateMessageBox(LPVOID lpParam) {
MessageBoxA(NULL, (char*)lpParam, "", MB_OK);
return 0;
}
CreateThread(NULL, 0, &CreateMessageBox, "Blah, Blah, Blah...", 0, NULL);
Also, you don't need to specify MB_APPLMODAL as it's default flag (it equals to 0).
If you are targeting modern Windows OS, it's better to have UNICODE defined, because MessageBoxA will convert you strings to UTF-16 and call MessageBoxW
What is the best way to create a thread for a message box, without having it glitch up?
In general, you don't.
Under Windows, all the windows (small 'w', meaning individual GUI elements here) in an application "run" in a single thread. This is generally the "main" thread -- but in particular, it is the thread in which the message pump is running. See my linked post for more details on the message pump.
If what you are truly trying to achieve is a dialog box or some other kind of window that can run concurrently to other windows running, so that it can remain up while other windows are still responsive to user input, then you want a modeless window or dialog box. This is a window that doesn't block other windows from processing updates or accepting user input. See here for a description of how to implement this using MFC, but note that you don't need to use MFC in order to implement a modeless dialog box.
Old question, new answer...
If the thread being invoked is being called into existence by a process that immediately exits (say you're running an executable that uses a VC++ DLL which pops a message box) then the thread will never have a chance to execute.
I had created a VC++ executable for testing that ran a loadlibrary on my DLL and the DLL created various threads with debugging message boxes. Since my testing executable only called the DLL and then exited, it didn't work.
I was informed by a coworker that I needed to add a sleep to the end of the testing executable that is using the DLL file in order for it to work.
Sure enough, it fixed it. This makes sense too, especially in the context of a DLL. Most applications loop until instructed to exit; my test application did not.
Be mindful of how your application is behaving!

MessageBox with timeout OR Closing a MessageBox from another thread

If my application crashes, I use an ExceptionFilter to catch the crash, perform some final actions, then show a message box to the user that the application has crashed.
Because the application already crashed, there's not much I can (or I dare) to do, because if I do too much, the executed code might access corrupted memory and crash again.
Some of the things I currently can't do (or I don't dare to do) is to close network connections, Oracle database sessions, ...
Problem is that if an application crashes, and the user is out to lunch while the MessageBox is open, other users might be blocked, because of the open database session. Therefore I want:
Either a MessageBox with a time-out. Problem is that you can't do this with the standard MessageBox Win32 API function, and I don't want to make a specific dialog for it (because I want to minimize the executed logic after the crash)
Or the possibility to close the MessageBox from another thread (the other thread can provide the time-out logic).
Did I overlook something in the Win32 API and is there a possibility to have a MessageBox with a time-out?
Or what is the correct way to close an open MessageBox from another thread (how to get the MessageBox handle, how to close it, ...)?
While I agree that spawning a new process to display a fire-and-forget dialog is probably best, FWIW there is actually a timeoutable messagebox function exported from user32 on XP & above; MessageBoxTimeout (as used by things like WShell.Popup())
Quick copy/paste solution:
int DU_MessageBoxTimeout(HWND hWnd, const WCHAR* sText, const WCHAR* sCaption, UINT uType, DWORD dwMilliseconds)
{
// Displays a message box, and dismisses it after the specified timeout.
typedef int(__stdcall *MSGBOXWAPI)(IN HWND hWnd, IN LPCWSTR lpText, IN LPCWSTR lpCaption, IN UINT uType, IN WORD wLanguageId, IN DWORD dwMilliseconds);
int iResult;
HMODULE hUser32 = LoadLibraryA("user32.dll");
if (hUser32)
{
auto MessageBoxTimeoutW = (MSGBOXWAPI)GetProcAddress(hUser32, "MessageBoxTimeoutW");
iResult = MessageBoxTimeoutW(hWnd, sText, sCaption, uType, 0, dwMilliseconds);
FreeLibrary(hUser32);
}
else
iResult = MessageBox(hWnd, sText, sCaption, uType); // oups, fallback to the standard function!
return iResult;
}
You should ask yourself, why you want a messagebox in the first place. When it is OK that the message box is not seen when noone is sitting in front of the computer, why isn't it OK that the user doesn't see a message when his program disappears?
If you really want it, I think the simplest solution is to spawn a new process displaying the message. It can run as long as it wants and does not interfer with your crashing program.
I noticed that if the main thread simply exits the application while the other thread still has the ::MessageBox open, that the MessageBox is being adopted by a process called CSRSS. This solves my problem, since this only requires a time-out on the Event in the main thread (WaitForSingleObject with timeout).
However, this raised another question: https://stackoverflow.com/questions/3091915/explanation-why-messagebox-of-exited-application-is-adopted-by-winsrv.
This does not justify a thread.
The best solution would be to use a modal dialog box that registers a timer for auto-close.
What about just logging the event to a local file (and record memory dumps or whatever information you might need for later debugging)?
You could close your application, close network connections and do your housekeeping stuff.
As soon as the application is started again, you can inform your user (based on local file information) that the application has crashed during last execution.
A Win32 MessageBox really is a dialog, with a dialog message pump. You can therefore rely on standard Win32 timer messages (WM_TIMER). Send one to your own window, and when you do get it, dismiss the MessageBox by sending a WM_COMMAND/BN_CLICKED message to the ID_OK button.
The messagebox, since it's a dialog, will be class "#32770". Since it's the only dialog box you will have open, it's easy to find amongst your child windows.
I would run your original code from inside a wrapper application that does a CreateProcess and then a MsgWaitForMultipleObjects on the process handle (most process launching code samples use WaitForSingleObject, but you need to guard against messaging deadlock scenarios). Your watching process can then detect the failure of the spawned process, pop up its own timed-out dialog, and exit on user response or timeout.
I think that's the cleanest solution which prevents your unstable program having to execute any code.