Opening a Basic Math Input Control - c++

I am hoping someone might be able to help me out. My objective is to open a math input panel using C++ but the panel only opens for a split second before the program exits. Here is what I have tried.
cin.get();
system("PAUSE");
getchar();
All of the aforementioned attempts to keep the program open have resulted in the math input control window popping up but staying blank.
The code that I am using is directly from here.
https://msdn.microsoft.com/en-us/library/windows/desktop/dd317324(v=vs.85).aspx
I am using Visual Studio Community Edition 2017 with Windows 10.
Any and all help is appreciated.
#include "stdafx.h"
#include "micaut.h"
#include "micaut_i.c"
#include "atlcomcli.h"
using namespace std;
int main()
{
CComPtr<IMathInputControl> g_spMIC; // Math Input Control
HRESULT hr = CoInitialize(NULL);
hr = g_spMIC.CoCreateInstance(CLSID_MathInputControl);
hr = g_spMIC->EnableExtendedButtons(VARIANT_TRUE);
hr = g_spMIC->Show();
return 0;
}

Your program shows the window but then terminates immediately. You will need to run a message loop to service the GUI.

Synchronization in a single-threaded apartment (STA) is implemented through window messages (see Understanding and Using COM Threading Models). This requires that you run a message loop in every STA thread.
#include <windows.h>
#include <micaut.h>
#include <micaut_i.c>
#include <atlcomcli.h>
int main() {
HRESULT hr = ::CoInitialize(NULL);
CComPtr<IMathInputControl> g_spMIC; // Math Input Control
if ( SUCCEEDED( hr ) ) {
hr = g_spMIC.CoCreateInstance(CLSID_MathInputControl);
}
if ( SUCCEEDED( hr ) ) {
hr = g_spMIC->EnableExtendedButtons(VARIANT_TRUE);
}
if ( SUCCEEDED( hr ) ) {
hr = g_spMIC->Show();
}
if ( SUCCEEDED( hr ) ) {
// Message loop for STA
MSG msg{ 0 };
while ( ::GetMessageW( &msg, nullptr, 0, 0 ) ) {
// MathInputControl sends WM_USER + 2 when it should close
if ( msg.message == ( WM_USER + 2 ) )
break;
::TranslateMessage( &msg );
::DispatchMessageW( &msg );
}
::CoUninitialize();
}
}
The Math Input Control sending a WM_USER + 2 message in response to clicking the Close or Cancel buttons is not part of the documented contract. A proper implementation would implement an _IMathInputControlEvents, and respond to its Close event instead.

Related

Hide desktop icons (c++)(SHGetSetSetting) [duplicate]

The answers I've found link to fHideIcon, but I get a 404 error on Microsoft's page for those links.
I've also tried:
SHELLSTATE ss;
SecureZeroMemory(&ss, sizeof(ss));
SHGetSetSettings(&ss, SSF_HIDEICONS, TRUE);
But that didn't work.
Does anyone know how to do this?
The following approach which uses the official shell API is a little bit involved, but works even under Windows 10.
Steps:
Get the IFolderView2 interface of the desktop (supported since Windows Vista).
Call IFolderView2::SetCurrentFolderFlags() with FWF_NOICONS for both the dwMask and dwFlags parameters.
The effect of the flag is visible immediately. There is no need to restart the computer nor "explorer.exe". The flag also persists after logoff or reboot.
The tricky thing is step 1). Raymond Chen shows C++ code for that in his article "Manipulating the positions of desktop icons", specifically in his FindDesktopFolderView() function.
Here is a full example in form of a console application. It is based on Raymond Chen's code. The program toggles the visibility of the desktop icons each time it is run.
The code has been tested under Windows 10 Version 1803.
"Library" code:
#include <ShlObj.h> // Shell API
#include <atlcomcli.h> // CComPtr & Co.
#include <string>
#include <iostream>
#include <system_error>
// Throw a std::system_error if the HRESULT indicates failure.
template< typename T >
void ThrowIfFailed( HRESULT hr, T&& msg )
{
if( FAILED( hr ) )
throw std::system_error{ hr, std::system_category(), std::forward<T>( msg ) };
}
// RAII wrapper to initialize/uninitialize COM
struct CComInit
{
CComInit() { ThrowIfFailed( ::CoInitialize( nullptr ), "CoInitialize failed" ); }
~CComInit() { ::CoUninitialize(); }
CComInit( CComInit const& ) = delete;
CComInit& operator=( CComInit const& ) = delete;
};
// Query an interface from the desktop shell view.
void FindDesktopFolderView( REFIID riid, void **ppv, std::string const& interfaceName )
{
CComPtr<IShellWindows> spShellWindows;
ThrowIfFailed(
spShellWindows.CoCreateInstance( CLSID_ShellWindows ),
"Failed to create IShellWindows instance" );
CComVariant vtLoc( CSIDL_DESKTOP );
CComVariant vtEmpty;
long lhwnd;
CComPtr<IDispatch> spdisp;
ThrowIfFailed(
spShellWindows->FindWindowSW(
&vtLoc, &vtEmpty, SWC_DESKTOP, &lhwnd, SWFO_NEEDDISPATCH, &spdisp ),
"Failed to find desktop window" );
CComQIPtr<IServiceProvider> spProv( spdisp );
if( ! spProv )
ThrowIfFailed( E_NOINTERFACE, "Failed to get IServiceProvider interface for desktop" );
CComPtr<IShellBrowser> spBrowser;
ThrowIfFailed(
spProv->QueryService( SID_STopLevelBrowser, IID_PPV_ARGS( &spBrowser ) ),
"Failed to get IShellBrowser for desktop" );
CComPtr<IShellView> spView;
ThrowIfFailed(
spBrowser->QueryActiveShellView( &spView ),
"Failed to query IShellView for desktop" );
ThrowIfFailed(
spView->QueryInterface( riid, ppv ),
"Could not query desktop IShellView for interface " + interfaceName );
}
Example to toggle desktop icons using the above code:
void ToggleDesktopIcons()
{
CComPtr<IFolderView2> spView;
FindDesktopFolderView( IID_PPV_ARGS(&spView), "IFolderView2" );
DWORD flags = 0;
ThrowIfFailed(
spView->GetCurrentFolderFlags( &flags ),
"GetCurrentFolderFlags failed" );
ThrowIfFailed(
spView->SetCurrentFolderFlags( FWF_NOICONS, flags ^ FWF_NOICONS ),
"SetCurrentFolderFlags failed" );
}
int wmain(int argc, wchar_t **argv)
{
try
{
CComInit init;
ToggleDesktopIcons();
std::cout << "Desktop icons have been toggled.\n";
}
catch( std::system_error const& e )
{
std::cout << "ERROR: " << e.what() << ", error code: " << e.code() << "\n";
return 1;
}
return 0;
}
The third parameter isn't about changing the setting, it's to select the SHGetSetSettings() behavior.
FALSE will get the value of the current setting and store it in ss, TRUE will set the value of the setting to what is in ss.
So basically you have to do ss.fHideIcons = TRUE and then call SHGetSetSettings(&ss, SSF_HIDEICONS, TRUE) to set it.
I know, it's weird, but on the other hand it allows you to change multiple settings simultaneously because SSF_* is a bitmask.
The following seems to work (adapted from https://stackoverflow.com/a/6403014/5743288):
#include <windows.h>
int main ()
{
HWND hProgman = FindWindowW (L"Progman", L"Program Manager");
HWND hChild = GetWindow (hProgman, GW_CHILD);
ShowWindow (hChild, SW_HIDE);
Sleep (2000);
ShowWindow (hChild, SW_SHOW);
}
Please note: this approach is not supported by Microsoft and disables right-clicking on ths desktop.

How to hide Desktop icons with Windows API in C++?

The answers I've found link to fHideIcon, but I get a 404 error on Microsoft's page for those links.
I've also tried:
SHELLSTATE ss;
SecureZeroMemory(&ss, sizeof(ss));
SHGetSetSettings(&ss, SSF_HIDEICONS, TRUE);
But that didn't work.
Does anyone know how to do this?
The following approach which uses the official shell API is a little bit involved, but works even under Windows 10.
Steps:
Get the IFolderView2 interface of the desktop (supported since Windows Vista).
Call IFolderView2::SetCurrentFolderFlags() with FWF_NOICONS for both the dwMask and dwFlags parameters.
The effect of the flag is visible immediately. There is no need to restart the computer nor "explorer.exe". The flag also persists after logoff or reboot.
The tricky thing is step 1). Raymond Chen shows C++ code for that in his article "Manipulating the positions of desktop icons", specifically in his FindDesktopFolderView() function.
Here is a full example in form of a console application. It is based on Raymond Chen's code. The program toggles the visibility of the desktop icons each time it is run.
The code has been tested under Windows 10 Version 1803.
"Library" code:
#include <ShlObj.h> // Shell API
#include <atlcomcli.h> // CComPtr & Co.
#include <string>
#include <iostream>
#include <system_error>
// Throw a std::system_error if the HRESULT indicates failure.
template< typename T >
void ThrowIfFailed( HRESULT hr, T&& msg )
{
if( FAILED( hr ) )
throw std::system_error{ hr, std::system_category(), std::forward<T>( msg ) };
}
// RAII wrapper to initialize/uninitialize COM
struct CComInit
{
CComInit() { ThrowIfFailed( ::CoInitialize( nullptr ), "CoInitialize failed" ); }
~CComInit() { ::CoUninitialize(); }
CComInit( CComInit const& ) = delete;
CComInit& operator=( CComInit const& ) = delete;
};
// Query an interface from the desktop shell view.
void FindDesktopFolderView( REFIID riid, void **ppv, std::string const& interfaceName )
{
CComPtr<IShellWindows> spShellWindows;
ThrowIfFailed(
spShellWindows.CoCreateInstance( CLSID_ShellWindows ),
"Failed to create IShellWindows instance" );
CComVariant vtLoc( CSIDL_DESKTOP );
CComVariant vtEmpty;
long lhwnd;
CComPtr<IDispatch> spdisp;
ThrowIfFailed(
spShellWindows->FindWindowSW(
&vtLoc, &vtEmpty, SWC_DESKTOP, &lhwnd, SWFO_NEEDDISPATCH, &spdisp ),
"Failed to find desktop window" );
CComQIPtr<IServiceProvider> spProv( spdisp );
if( ! spProv )
ThrowIfFailed( E_NOINTERFACE, "Failed to get IServiceProvider interface for desktop" );
CComPtr<IShellBrowser> spBrowser;
ThrowIfFailed(
spProv->QueryService( SID_STopLevelBrowser, IID_PPV_ARGS( &spBrowser ) ),
"Failed to get IShellBrowser for desktop" );
CComPtr<IShellView> spView;
ThrowIfFailed(
spBrowser->QueryActiveShellView( &spView ),
"Failed to query IShellView for desktop" );
ThrowIfFailed(
spView->QueryInterface( riid, ppv ),
"Could not query desktop IShellView for interface " + interfaceName );
}
Example to toggle desktop icons using the above code:
void ToggleDesktopIcons()
{
CComPtr<IFolderView2> spView;
FindDesktopFolderView( IID_PPV_ARGS(&spView), "IFolderView2" );
DWORD flags = 0;
ThrowIfFailed(
spView->GetCurrentFolderFlags( &flags ),
"GetCurrentFolderFlags failed" );
ThrowIfFailed(
spView->SetCurrentFolderFlags( FWF_NOICONS, flags ^ FWF_NOICONS ),
"SetCurrentFolderFlags failed" );
}
int wmain(int argc, wchar_t **argv)
{
try
{
CComInit init;
ToggleDesktopIcons();
std::cout << "Desktop icons have been toggled.\n";
}
catch( std::system_error const& e )
{
std::cout << "ERROR: " << e.what() << ", error code: " << e.code() << "\n";
return 1;
}
return 0;
}
The third parameter isn't about changing the setting, it's to select the SHGetSetSettings() behavior.
FALSE will get the value of the current setting and store it in ss, TRUE will set the value of the setting to what is in ss.
So basically you have to do ss.fHideIcons = TRUE and then call SHGetSetSettings(&ss, SSF_HIDEICONS, TRUE) to set it.
I know, it's weird, but on the other hand it allows you to change multiple settings simultaneously because SSF_* is a bitmask.
The following seems to work (adapted from https://stackoverflow.com/a/6403014/5743288):
#include <windows.h>
int main ()
{
HWND hProgman = FindWindowW (L"Progman", L"Program Manager");
HWND hChild = GetWindow (hProgman, GW_CHILD);
ShowWindow (hChild, SW_HIDE);
Sleep (2000);
ShowWindow (hChild, SW_SHOW);
}
Please note: this approach is not supported by Microsoft and disables right-clicking on ths desktop.

CreateProcess( ) doesn't create a new window with CREATE_NEW_CONSOLE flag - C/C++

I've been trying to create a process with CreateProcess() using the Windows API of course. I haven't been able to create a new console for some reason even after scouring the web.
Reasearch I've Done :
I used the MSDN example code as a base for the parameters I should use in the function :
http://msdn.microsoft.com/en-us/library/windows/desktop/ms682512%28v=vs.85%29.aspx
I read the following MSDN article for information on how you should create new console windows :
http://msdn.microsoft.com/en-us/library/windows/desktop/ms682528%28v=vs.85%29.aspx
I also read a similar SO problem to mine about someone having the same problem :
CreateProcess does not create additional console windows under Windows 7?
Results :
I've written the code I will post below with all the requirements needed to create a new console, but it doesn't behave as expected. I've spent a long time trying to find the answer on my own, but the articles above were the only relevant ones I could find through google. What happens is that the process is created, but it is inside my C program's console. I want to be able to create the process without it inherting my program's console.
There are also other discrepancies as well. If I print lots of characters in my do-while loop without a Sleep() to slow it down, TerminateProcess() will fail with Access Denied and the program will crash when I press the escape key. This is also not desired behavior.
Here is the C program that I have right now :
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define WIN32_LEAN_AND_MEAN
#include <process.h>
#include <windows.h>
#define IS_PRESSED( vk ) ( GetAsyncKeyState( vk ) & 0x8000 )
typedef struct process
{
PROCESS_INFORMATION p_info;
STARTUPINFO s_info;
} process;
void win_error( char * message, int is_exit )
{
char buffer[BUFSIZ] = { 0 };
DWORD error_code = GetLastError( );
FormatMessage
(
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
error_code,
MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ),
( LPTSTR ) buffer,
BUFSIZ,
NULL
);
MessageBox( NULL, buffer, message, MB_ICONWARNING | MB_OK );
if ( is_exit ) exit( error_code );
return;
}
int create_process( process * p, const char * exe_path, const char * cmd_line_args )
{
p->s_info.cb = sizeof( STARTUPINFO );
p->s_info.dwFlags |= CREATE_NEW_CONSOLE;
return CreateProcess(
exe_path,
( LPSTR )cmd_line_args,
NULL,
NULL,
FALSE,
0,
NULL,
NULL,
&p->s_info,
&p->p_info
);
}
int main( )
{
process p = { { 0 }, { 0 } };
srand( time( NULL ) );
if ( !create_process( &p, "J:\\C programs and compiliers\\C\\WindowsTest\\bin\\Debug\\matrix.bat", NULL ) )
win_error( "CreateProcess", 1 );
CloseHandle( p.p_info.hThread );
do
{
if ( IS_PRESSED( VK_ESCAPE ) )
if ( !TerminateProcess( p.p_info.hProcess, 0 ) )
win_error( "TerminateProcess", 0 );
Sleep( 50 );
} while ( WaitForSingleObject( p.p_info.hProcess, 0 ) != WAIT_OBJECT_0 );
CloseHandle( p.p_info.hProcess );
return 0;
}
Here is the Batch program I'm calling :
#echo off
setlocal enabledelayedexpansion
:start
echo Hello PSAPI on Windows...
pause >nul
exit
I'm expecting someone will know how to mess with processes more than I do. This is my first time using the CreateProcess() function. Yes, I am aware of ShellExecute(). I am also aware that my Batch file isn't a matrix, but I wanted to start simple.
CREATE_NEW_CONSOLE is a flag of CreateProcess() itself, not of STARTUPINFO. You are putting the flag in the wrong place. Try this instead:
int create_process( process * p, const char * exe_path, const char * cmd_line_args )
{
...
return CreateProcessA(
exe_path,
cmd_line_args,
NULL,
NULL,
FALSE,
CREATE_NEW_CONSOLE, // <-- here
NULL,
NULL,
&p->s_info,
&p->p_info
);
}
Also, keep in mind that a STARTUPINFOEX can be passed to CreateProcess(), so your create_process() function should not be forcing p->s_info.cb, that should be the caller's responsibility depending on whether a STARTUPINFO or a STARTUPINFOEX is being used.

Obtaining the Excel.Application IDispatch* within a dll that's been loaded into Excel

Does anyone know how to get hold of the Excel.Application IDispatch* pointer associated with an excel process into which an dll has been loaded?
A key thing here is that the process is excel.exe, and the pointer I need must belong to that process. Using the Running Object Table will not fly since Excel only registers its first instance with that.
I'm hoping there is some low-level COM trickery, but I'm not an expert in that field.
EDITED II Code is under the WTFPL license version 2.
EDITED: Add PID parameter to allow filtering when several Excel processes are currently running, as per comment suggestion from #EricBrown.
I managed to get a working IDispatch* to an Excel "Application" object without using the ROT. The trick is to use MSAA. My code works as a stand alone console application, but I think that if the code is executed in an Excel process, via DLL Injection, it MAY works fine. You may have to be in a dedicated thread. Let me know if you want me to push the expriment to the DLL injection level.
Tested OK on Window7 64b, with a UNICODE builds (32 bits and 64 bits).
Excel version 2010 64 bits (version "14")
I get the IDispatch via the "application" property from an "Worksheet" object. Consequence: there must be an opened worksheet. In order to find the good MSSA Window, I need the class name of the Top Level Excel Frame Window. In Excel 2010, it's "XLMAIN". The class name for worksheets is "EXCEL7" and that seems to be a "standard".
I was not able to directly get a working IDispatch* from the main Excel Window, but have not tried very hard. That may involve #import with a automation DLL from Excel, in order to QueryInterface the IDispatch that MSAA gives for the main Window (that IDispatch is NOT for an Application object)
#include <atlbase.h>
#pragma comment( lib, "Oleacc.lib" )
HRESULT GetExcelAppDispatch( CComPtr<IDispatch> & spIDispatchExcelApp, DWORD dwExcelPID ) {
struct ew {
struct ep {
_TCHAR* pszClassName;
DWORD dwPID;
HWND hWnd;
};
static BOOL CALLBACK ewp( HWND hWnd, LPARAM lParam ) {
TCHAR szClassName[ 64 ];
if ( GetClassName( hWnd, szClassName, 64 ) ) {
ep* pep = reinterpret_cast<ep*>( lParam );
if ( _tcscmp( szClassName, pep->pszClassName ) == 0 ) {
if ( pep->dwPID == 0 ) {
pep->hWnd = hWnd;
return FALSE;
} else {
DWORD dwPID;
if ( GetWindowThreadProcessId( hWnd, &dwPID ) ) {
if ( dwPID == pep->dwPID ) {
pep->hWnd = hWnd;
return FALSE;
}
}
}
}
}
return TRUE;
}
};
ew::ep ep;
ep.pszClassName = _TEXT( "XLMAIN" );
ep.dwPID = dwExcelPID;
ep.hWnd = NULL;
EnumWindows( ew::ewp, reinterpret_cast<LPARAM>( &ep ) );
HWND hWndExcel = ep.hWnd;
if ( ep.hWnd == NULL ) {
printf( "Can't Find Main Excel Window with EnumWindows\n" );
return -1;
}
ep.pszClassName = _TEXT( "EXCEL7" );
ep.dwPID = 0;
ep.hWnd = NULL;
EnumChildWindows( hWndExcel, ew::ewp, reinterpret_cast<LPARAM>( &ep ) );
HWND hWndWorkSheet = ep.hWnd;
if ( hWndWorkSheet == NULL ) {
printf( "Can't Find a WorkSheet with EnumChildWindows\n" );
return -1;
}
CComPtr<IDispatch> spIDispatchWorkSheet;
HRESULT hr = AccessibleObjectFromWindow( hWndWorkSheet, OBJID_NATIVEOM, IID_IDispatch,
reinterpret_cast<void**>( &spIDispatchWorkSheet ) );
if ( FAILED( hr ) || ( spIDispatchWorkSheet == 0 ) ) {
printf( "AccessibleObjectFromWindow Failed\n" );
return hr;
}
CComVariant vExcelApp;
hr = spIDispatchWorkSheet.GetPropertyByName( CComBSTR( "Application" ), &vExcelApp );
if ( SUCCEEDED( hr ) && ( vExcelApp.vt == VT_DISPATCH ) ) {
spIDispatchExcelApp = vExcelApp.pdispVal;
return S_OK;
}
return hr;
}
int _tmain(int argc, _TCHAR* argv[])
{
DWORD dwExcelPID = 0;
if ( argc > 1 ) dwExcelPID = _ttol( argv[ 1 ] );
HRESULT hr = CoInitialize( NULL );
bool bCoUnInitializeTodo = false;
if ( SUCCEEDED( hr ) ) {
bCoUnInitializeTodo = true;
CComPtr<IDispatch> spDispatchExcelApp;
hr = GetExcelAppDispatch( spDispatchExcelApp, dwExcelPID );
if ( SUCCEEDED( hr ) && spDispatchExcelApp ) {
CComVariant vExcelVer;
hr = spDispatchExcelApp.GetPropertyByName( CComBSTR( "Version" ), &vExcelVer );
if ( SUCCEEDED( hr ) && ( vExcelVer.vt == VT_BSTR ) ) {
wprintf( L"Excel Version is %s\n", vExcelVer.bstrVal );
}
}
}
if ( bCoUnInitializeTodo ) CoUninitialize();
return 0;
}
You should be able to find out how to do this by reviewing the code in ExcelDNA. This project contains code that hooks back into Excel from the extension library. The code is likely to be more elaborate that you need, but will implement the reference you require.
This is how I do it: (acknowledge #manuell). dispatch_wrapper is a class, here is the constructor to set m_disp_application:
dispatch_wrapper(void)
{
DWORD target_process_id = ::GetProcessId(::GetCurrentProcess());
if (getProcessName() == "excel.exe"){
HWND hwnd = ::FindWindowEx(0, 0, "XLMAIN", NULL);
while (hwnd){
DWORD process_id;
::GetWindowThreadProcessId(hwnd, &process_id);
if (process_id == target_process_id){
HWND hwnd_desk = ::FindWindowEx(hwnd, 0, "XLDESK", NULL);
HWND hwnd_7 = ::FindWindowEx(hwnd_desk, 0, "EXCEL7", NULL);
IDispatch* p = nullptr;
if (SUCCEEDED(::AccessibleObjectFromWindow(hwnd_7, OBJID_NATIVEOM, IID_IDispatch, (void**)&p))){
LPOLESTR name[1] = {L"Application"};
DISPID dispid;
if (SUCCEEDED(p->GetIDsOfNames(IID_NULL, name, 1U, LOCALE_SYSTEM_DEFAULT, &dispid))){
CComVariant v;
DISPPARAMS dp;
::memset(&dp, NULL, sizeof(DISPPARAMS));
EXCEPINFO ei;
::memset(&ei, NULL, sizeof(EXCEPINFO));
if (SUCCEEDED(p->Invoke(dispid, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_PROPERTYGET, &dp, &v, &ei, NULL))){
if (v.vt == VT_DISPATCH){
m_disp_application = v.pdispVal;
m_disp_application->AddRef();
return;
}
}
}
}
}
hwnd = ::FindWindowEx(0, hwnd, "XLMAIN", NULL);
}
}
m_disp_application = nullptr;
}
getProcessName() returns lower case.
Because Office applications register their documents in the ROT, you can attach to instances beside the first one (which is already in the ROT) by getting IDispatch for documents in the ROT, then you can use document.Application.hwnd (this is VBA, you need to translate to IDispatch::GetIDsOfNames and IDispatch::Invoke with DISPATCH_PROPERTYGET) to get the window handles of all Excel instances.
Now you have a mapping between IDispatch and Windows handles of all Excel instances, it is time to find your own Excel instance. You can call GetWindowThreadProcessId on the window handles to get the process ids, then compare to your own process id returned by GetCurrentProcessId to see which excel window belongs to your current process, and look up in the HWND to IDispatch mapping to find your current Excel application's IDispatch interface.

Shut down a ATL application cleanly

I have developed a console ATL application and want to trap the close?, exit?, terminate? event so that I can close log files and perform a general clean-up on exit.
How can I trap the 'terminate' event that would result from someone ending the .exe in the task manager?
EDIT:
It's a console application, I've attached the main class. Could you possibly point to where and how I should use SetConsoleCtrlHandler?
// Override CAtlExeModuleT members
int WinMain(int nShowCmd) throw()
{
if (CAtlBaseModule::m_bInitFailed) //ctor failed somewhere
{
ATLASSERT(0);
return -1;
}
HRESULT hr = S_OK;
LPTSTR lpCmdLine = GetCommandLine(); //this line necessary for _ATL_MIN_CRT
if( ParseCommandLine( lpCmdLine, &hr ) )
{
if( SUCCEEDED( RegisterClassObjects( CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE ) ) )
{
CComPtr<IRORCAdapterMain> pAdapter;
if( SUCCEEDED( pAdapter.CoCreateInstance( L"RORCAdapter.RORCAdapterMain" ) ) )
{
if( SUCCEEDED( pAdapter->StartAdapter() ) )
{
MSG msg;
while( GetMessage( &msg, 0, 0, 0 ) )
DispatchMessage( &msg );
}
}
RevokeClassObjects();
}
}
You can't trap "End Process" from the Processes tab in Task Manager. If a program could trap it, how would you kill it?
To respond to "End Process" on the Applications tab in Task Manager, handle the WM_CLOSE message in your main window.
This assumes that your ATL app is a Windows GUI application. If it's a console application, you need to look at SetConsoleCtrlHandler.
Catching Ctrl-C / Ctrl-Break is not to hard.
Just call SetConsoleCtrlHandler to specify which call-back function should handle it.
(Hopefully) illustrating example:
#include <wincon.h>
bool g_terminate = false;
int main(void)
{
SetConsoleCtrlHandler( control_handler, TRUE );
while ( !g_terminate )
{
doWork();
}
}
int WINAPI control_handler ( DWORD dwCtrlType )
{
switch( dwCtrlType )
{
case CTRL_BREAK_EVENT:
case CTRL_C_EVENT:
g_terminate = true;
return 1;
default:
return 0;
}
}
/L
Off course, to have you example terminating, in control_handler replace
g_terminate = true;
with
PostMessage(HWND_BROADCAST, WM_CLOSE, 0, 0);