MFC DestroyWindow results in crash - c++

I'm having an issue with MFC. Whenever I call DestroyWindow on my modeless dialog, I crash with an unhandled exception in AfxThrowInvalidArgException.
Checking the callstack, it crashes on like 1055 in wincore.cpp:
ENSURE(pMap != NULL);
In case it's relevant, this is how I create the modeless window:
Dialogs::WelcomeDialog = new CRCChatWelcomeDlg( );
m_pMainWnd = Dialogs::WelcomeDialog;
Dialogs::WelcomeDialog->Create( DialogRCChatWelcome, CWnd::GetDesktopWindow( ) );
if ( pShellManager != nullptr )
delete pShellManager;
MSG Message;
while ( GetMessage( &Message, Dialogs::WelcomeDialog->m_hWnd, 0, 0 ) ) {
TranslateMessage( &Message );
DispatchMessage( &Message );
}
Dialogs::MainMenuDialog = new CRCChatMainMenuDlg( );
m_pMainWnd = Dialogs::MainMenuDialog;
Dialogs::MainMenuDialog->Create( DialogRCChatMainMenu );
while ( GetMessage( &Message, Dialogs::MainMenuDialog->m_hWnd, 0, 0 ) ) {
TranslateMessage( &Message );
DispatchMessage( &Message );
}
And I destroy it like this:
Dialogs::WelcomeDialog->DestroyWindow( );

Related

why openvr GetPoseActionDataForNextFrame is not getting position of controllers

I'm trying to create simple application using OpenVR and OpenGL. Headset tracking and rendering is working, but I'm not getting position of controllers.
Example code from here https://github.com/ValveSoftware/openvr/wiki/API-Documentation works, and is reading my controllers fine.
I'm using json file copied from that example.
Here is simplified version of my code:
vr::IVRSystem* vrSystem= vr::VR_Init( &eError, vr::VRApplication_Scene );
vrSystem->GetRecommendedRenderTargetSize( &vrScreenWidth, &vrScreenHeight );
initWinapi();
initOpenGL();
gladLoadGL();
createTexturesForVrRendering(vrScreenWidth,vrScreenHeight);
vrProjection[vr::Eye_Left] = ConvertSteamVRMatrix44ToMatrix4( vrSystem->GetProjectionMatrix( vr::Eye_Left , 0.001, 100.0 ) );
vrProjection[vr::Eye_Right]= ConvertSteamVRMatrix44ToMatrix4( vrSystem->GetProjectionMatrix( vr::Eye_Right, 0.001, 100.0 ) );
vrEyeTransform[vr::Eye_Left] = ConvertSteamVRMatrix34ToMatrix4( vrSystem->GetEyeToHeadTransform( vr::Eye_Left ) );
vrEyeTransform[vr::Eye_Left].invert();
vrEyeTransform[vr::Eye_Right]= ConvertSteamVRMatrix34ToMatrix4( vrSystem->GetEyeToHeadTransform( vr::Eye_Right ) );
vrEyeTransform[vr::Eye_Right].invert();
compileShaders();
vr::VRCompositor();
vr::VRActionSetHandle_t actionsetDemo = vr::k_ulInvalidActionSetHandle;
vr::VRActionHandle_t handLeftPositionAction = vr::k_ulInvalidActionHandle;
vr::VRActionHandle_t handRightPositionAction = vr::k_ulInvalidActionHandle;
vr::VRActionHandle_t m_actionHideCubes= vr::k_ulInvalidActionHandle;
vr::VRInput()->SetActionManifestPath( "C:\\src\\helloWorldVr\\openvr_actions.json" );
vr::VRInput()->GetActionHandle( "/actions/demo/in/HideCubes", &m_actionHideCubes );
vr::VRInput()->GetActionSetHandle( "/actions/demo", &actionsetDemo );
vr::VRInput()->GetActionHandle( "/actions/demo/in/Hand_Left", &handLeftPositionAction );
vr::VRInput()->GetActionHandle( "/actions/demo/in/Hand_Right", &handRightPositionAction );
while( appStillRunning ){
static vr::TrackedDevicePose_t m_rTrackedDevicePose[vr::k_unMaxTrackedDeviceCount];
vr::VRCompositor()->WaitGetPoses( m_rTrackedDevicePose, vr::k_unMaxTrackedDeviceCount, NULL, 0 );
if( m_rTrackedDevicePose[vr::k_unTrackedDeviceIndex_Hmd].bPoseIsValid ){
vrHeadPosInv = Matrix4(
m_rTrackedDevicePose[vr::k_unTrackedDeviceIndex_Hmd].mDeviceToAbsoluteTracking.m[0][0], m_rTrackedDevicePose[vr::k_unTrackedDeviceIndex_Hmd].mDeviceToAbsoluteTracking.m[1][0], m_rTrackedDevicePose[vr::k_unTrackedDeviceIndex_Hmd].mDeviceToAbsoluteTracking.m[2][0], 0.0,
m_rTrackedDevicePose[vr::k_unTrackedDeviceIndex_Hmd].mDeviceToAbsoluteTracking.m[0][1], m_rTrackedDevicePose[vr::k_unTrackedDeviceIndex_Hmd].mDeviceToAbsoluteTracking.m[1][1], m_rTrackedDevicePose[vr::k_unTrackedDeviceIndex_Hmd].mDeviceToAbsoluteTracking.m[2][1], 0.0,
m_rTrackedDevicePose[vr::k_unTrackedDeviceIndex_Hmd].mDeviceToAbsoluteTracking.m[0][2], m_rTrackedDevicePose[vr::k_unTrackedDeviceIndex_Hmd].mDeviceToAbsoluteTracking.m[1][2], m_rTrackedDevicePose[vr::k_unTrackedDeviceIndex_Hmd].mDeviceToAbsoluteTracking.m[2][2], 0.0,
m_rTrackedDevicePose[vr::k_unTrackedDeviceIndex_Hmd].mDeviceToAbsoluteTracking.m[0][3], m_rTrackedDevicePose[vr::k_unTrackedDeviceIndex_Hmd].mDeviceToAbsoluteTracking.m[1][3], m_rTrackedDevicePose[vr::k_unTrackedDeviceIndex_Hmd].mDeviceToAbsoluteTracking.m[2][3], 1.0f
);
vrHeadPosInv.invert();
}
while( PeekMessage( &msg, 0, 0, 0, PM_REMOVE ) ){
TranslateMessage( &msg );
DispatchMessage( &msg );
}
vr::VREvent_t event;
while( vrSystem->PollNextEvent( &event, sizeof( event ) ) ){}
vr::VRActiveActionSet_t actionSet = { 0 };
actionSet.ulActionSet = actionsetDemo;
vr::VRInput()->UpdateActionState( &actionSet, sizeof( actionSet ), 1 );
vr::InputPoseActionData_t poseData;
vr::EVRInputError res = vr::VRInput()->GetPoseActionDataForNextFrame( handLeftPositionAction, vr::TrackingUniverseStanding, &poseData, sizeof( poseData ), vr::k_ulInvalidInputValueHandle );
if( res == vr::VRInputError_None ){
if( poseData.bActive && poseData.pose.bPoseIsValid ){ /// poseData.bActive is always false
vrHandPos[vr::Eye_Left]= vrHmdMatrix34_t2Matrix4( poseData.pose.mDeviceToAbsoluteTracking );
}
}
res = vr::VRInput()->GetPoseActionDataForNextFrame( handRightPositionAction, vr::TrackingUniverseStanding, &poseData, sizeof( poseData ), vr::k_ulInvalidInputValueHandle );
if( res == vr::VRInputError_None ){
if( poseData.bActive && poseData.pose.bPoseIsValid ){ /// poseData.bActive is always false
vrHandPos[vr::Eye_Right] = vrHmdMatrix34_t2Matrix4( poseData.pose.mDeviceToAbsoluteTracking );
}
}
renderScene();
vr::Texture_t leftEyeTexture = { (void*)(uintptr_t)vrScreenTexture[0], vr::TextureType_OpenGL, vr::ColorSpace_Gamma };
vr::VRCompositor()->Submit( vr::Eye_Left, &leftEyeTexture );
vr::Texture_t rightEyeTexture = { (void*)(uintptr_t)vrScreenTexture[1], vr::TextureType_OpenGL, vr::ColorSpace_Gamma };
vr::VRCompositor()->Submit( vr::Eye_Right, &rightEyeTexture );
glFinish();
SwapBuffers( hdc );
glClearColor( 0, 0, 0, 1 );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glFlush();
glFinish();
}
vr::VR_Shutdown();
shutDownOpenGL();
Am I missing something ?

Checking if another window is closed c++

I'm developing an application that checks open windows on a user computer on Windows (just like the Task Manager)
I used EnumWindows to list all the active window and it works, now i want to create a function that write a message on the console when a windows has been closed. Is possible or i have to check an array of WindowHandler in a separate thread and how do I check their status?
Thank for the help.
The easiest solution is to use WinEvents, by registering for EVENT_OBJECT_DESTROY events. The code is fairly straight forward:
#include <windows.h>
namespace {
HWINEVENTHOOK g_WindowDestructionHook = NULL;
}
inline void CALLBACK WinEventProc( HWINEVENTHOOK hWinEventHook,
DWORD event,
HWND hwnd,
LONG idObject,
LONG idChild,
DWORD dwEventThread,
DWORD dwmsEventTime ) {
// Filter interesting events only:
if ( idObject == OBJID_WINDOW && idChild == CHILDID_SELF ) {
wprintf( L"Window destroyed: HWND = %08X\n", hwnd );
}
}
inline void RegisterWindowDestructionHook() {
g_WindowDestructionHook = ::SetWinEventHook( EVENT_OBJECT_DESTROY,
EVENT_OBJECT_DESTROY,
NULL,
WinEventProc,
0, 0,
WINEVENT_OUTOFCONTEXT );
}
inline void UnregisterHook() {
::UnhookWinEvent( g_WindowDestructionHook );
}
Using this is equally simple:
::CoInitialize( NULL );
RegisterWindowDestructionHook();
MSG msg = {};
while ( ::GetMessageW( &msg, nullptr, 0, 0 ) > 0 ) {
::TranslateMessage( &msg );
::DispatchMessageW( &msg );
}
UnregisterHook();
::CoUninitialize();

Win32 Handling Internal Paint Messages

I am running a Win32 application in debug mode using Visual Studio. After switching to Visual Studio to debug my application does not continue its message loop...no messages are being sent...How do I handle focus/activation messages in order to resume the message loop?
EDIT:
This application uses DirectX9. I have 2 viewports( device swapchains ) to which I render geometry. If, during runtime, I click on a different window and then later try to return to my application both viewports are black( not being rendered to ). I set breakpoints in the message loop and am finding that one message( WM_PAINT ) is constantly being translated and dispatched, thus preventing my application from rendering. Below is message loop. 'bGotMsg' is always true after returning focus to my application...
EDIT: The problem seems to be an internal WM_PAINT message that is not being handled...I've checked the message that is continually being dispatched and the window handle is not one of my application...could it be some internal handle? MSDN indicates here that a WM_PAINT message will be sent while no other messages are in the queue or until the internal paint message is handled...How do I handle this message?
HRESULT WINAPI GDEMainLoop( HACCEL hAccel )
{
HRESULT hr =S_OK;
HWND hWnd = DXUTGetHWND();
// Now we're ready to receive and process Windows messages.
bool bGotMsg;
MSG msg;
msg.message = WM_NULL;
PeekMessage( &msg, NULL, 0U, 0U, PM_NOREMOVE );
while( WM_QUIT != msg.message )
{
// Use PeekMessage() so we can use idle time to render the scene.
bGotMsg = ( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) != 0 );
if( bGotMsg )
{
// Translate and dispatch the message
if( /*!TranslateAccelerator( hWnd, hAccel, &msg )*/
!IsDialogMessage( wnd.GetWindow( CWindowManager::EXPLORERBAR ), &msg )
&& !IsDialogMessage( wnd.GetSceneOutliner()->GetHWND(), &msg )
&& !IsDialogMessage( wnd.GetResourceOutliner()->GetHWND(), &msg )
&& !IsDialogMessage( wnd.GetProjectOutliner()->GetHWND(), &msg )
&& !IsDialogMessage( wnd.GetProjectDialog()->GetHWND(), &msg )
&& !IsDialogMessage( wnd.GetSceneDialog()->GetHWND(), &msg ) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
}
else
{
if( FAILED( hr = GDERender3DEnvironment() ) )
{
DebugStringDX( MainClassName, "Failed to GDERender3DEnvironment() at GDEMainLoop()", __LINE__, hr );
Alert( NULL,
L"A failure occured while trying to render the 3D environment!",
L"Render Failure" );
PostQuitMessage( 0 );
}
}
}
return S_OK;
}

Filter System processes from user processes

I need to know how can I filter current user files/processes from operating system processes ?
I have listed all the current running files through the attached code in C++ .
now, i need to know how can i show only user files from this list?
Is there any demarcation parameter for this!!
#include <windows.h>
#include <tlhelp32.h>
#include <tchar.h>
// Forward declarations:
BOOL GetProcessList( );
BOOL ListProcessModules( DWORD dwPID );
void printError( TCHAR* msg );
int main( void )
{
GetProcessList( );
return 0;
}
BOOL GetProcessList( )
{
HANDLE hProcessSnap;
HANDLE hProcess;
PROCESSENTRY32 pe32;
// Take a snapshot of all processes in the system.
hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
if( hProcessSnap == INVALID_HANDLE_VALUE )
{
printError( TEXT("CreateToolhelp32Snapshot (of processes)") );
return( FALSE );
}
// Set the size of the structure before using it.
pe32.dwSize = sizeof( PROCESSENTRY32 );
// Retrieve information about the first process,
// and exit if unsuccessful
if( !Process32First( hProcessSnap, &pe32 ) )
{
printError( TEXT("Process32First") ); // show cause of failure
CloseHandle( hProcessSnap ); // clean the snapshot object
return( FALSE );
}
// Now walk the snapshot of processes, and
// display information about each process in turn
do
{
_tprintf( TEXT("\n\n=====================================================" ));
_tprintf( TEXT("\nPROCESS NAME: %s"), pe32.szExeFile );
// List the modules and threads associated with this process
ListProcessModules( pe32.th32ProcessID );
} while( Process32Next( hProcessSnap, &pe32 ) );
CloseHandle( hProcessSnap );
return( TRUE );
}
BOOL ListProcessModules( DWORD dwPID )
{
HANDLE hModuleSnap = INVALID_HANDLE_VALUE;
MODULEENTRY32 me32;
// Take a snapshot of all modules in the specified process.
hModuleSnap = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE, dwPID );
if( hModuleSnap == INVALID_HANDLE_VALUE )
{
printError( TEXT("CreateToolhelp32Snapshot (of modules)") );
return( FALSE );
}
// Set the size of the structure before using it.
me32.dwSize = sizeof( MODULEENTRY32 );
// Retrieve information about the first module,
// and exit if unsuccessful
if( !Module32First( hModuleSnap, &me32 ) )
{
printError( TEXT("Module32First") ); // show cause of failure
CloseHandle( hModuleSnap ); // clean the snapshot object
return( FALSE );
}
// Now walk the module list of the process,
// and display information about each module
do
{
_tprintf( TEXT("\n\n MODULE NAME: %s"), me32.szModule );
_tprintf( TEXT("\n Executable = %s"), me32.szExePath );
} while( Module32Next( hModuleSnap, &me32 ) );
CloseHandle( hModuleSnap );
return( TRUE );
}
void printError( TCHAR* msg )
{
DWORD eNum;
TCHAR sysMsg[256];
TCHAR* p;
eNum = GetLastError( );
FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, eNum,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
sysMsg, 256, NULL );
// Trim the end of the line and terminate it with a null
p = sysMsg;
while( ( *p > 31 ) || ( *p == 9 ) )
++p;
do { *p-- = 0; } while( ( p >= sysMsg ) &&
( ( *p == '.' ) || ( *p < 33 ) ) );
// Display the message
_tprintf( TEXT("\n WARNING: %s failed with error %d (%s)"), msg, eNum, sysMsg );
}

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);