Winapi: Could not register Signal handlers - windows

Here is my code:
#include <windows.h>
#include <stdio.h>
BOOL CtrlHandler( DWORD fdwCtrlType )
{
printf("I'm In...\n");
fflush(stdout);
switch( fdwCtrlType )
{
// Handle the CTRL-C signal.
case CTRL_C_EVENT:
printf( "Ctrl-C event\n\n" );
fflush(stdout);
Beep( 750, 300 );
return( TRUE );
// CTRL-CLOSE: confirm that the user wants to exit.
case CTRL_CLOSE_EVENT:
Beep( 600, 200 );
printf( "Ctrl-Close event\n\n" );
fflush(stdout);
return( TRUE );
// Pass other signals to the next handler.
case CTRL_BREAK_EVENT:
Beep( 900, 200 );
printf( "Ctrl-Break event\n\n" );
fflush(stdout);
return FALSE;
case CTRL_LOGOFF_EVENT:
Beep( 1000, 200 );
printf( "Ctrl-Logoff event\n\n" );
fflush(stdout);
return FALSE;
case CTRL_SHUTDOWN_EVENT:
Beep( 750, 500 );
printf( "Ctrl-Shutdown event\n\n" );
fflush(stdout);
return FALSE;
default:
return FALSE;
}
}
int main( void )
{
if( SetConsoleCtrlHandler( (PHANDLER_ROUTINE) CtrlHandler, TRUE ) )
{
printf( "\nThe Control Handler is installed.\n" );
printf( "\n -- Now try pressing Ctrl+C or Ctrl+Break, or" );
printf( "\n try logging off or closing the console...\n" );
printf( "\n(...waiting in a loop for events...)\n\n" );
fflush(stdout);
while( 1 ){ }
}
else
{
printf( "\nERROR: Could not set control handler");
fflush(stdout);
return 1;
}
return 0;
}
As you Can see I'm using example provided in msdn website, but my problem is that, when I launch application The Control Handler is installed.
-- Now try pressing Ctrl+C or Ctrl+Break, or
try logging off or closing the console...
(...waiting in a loop for events...) gets printed but when I hit CTR+C nothing happens(nothing gets printed) and process terminates. I've added fflush function in several places to make sure thats it's not printing problem. Thanks.

Related

Handle SDL_KeyboardEvent without window focus

I'm trying to get keyboard events using SDL2.0. The following sample is working for me when I have the window's focus:
#include <SDL2/SDL.h>
int main(int argc, char* argv[])
{
if (SDL_Init(SDL_INIT_VIDEO) != 0) /* Prefer only events SDL_INIT_EVENTS */
{
SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
return 1;
}
SDL_Window* gWindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 320, SDL_WINDOW_SHOWN ); /* I don't want this window! */
/* While no quit */
bool quit = false;
//Event handler
SDL_Event e;
//While application is running
while( !quit )
{
//Handle events on queue
while( SDL_PollEvent( &e ) != 0 )
{
//User requests quit
if( e.type == SDL_QUIT )
{
quit = true;
}
//User presses a key
else if( e.type == SDL_KEYDOWN )
{
printf( "Key type: %d\n", e.key.keysym.sym );
//Select surfaces based on key press
switch( e.key.keysym.sym )
{
case SDLK_UP:
printf( "UP!\n" );
break;
case SDLK_DOWN:
printf( "DOWN!\n" );
break;
case SDLK_LEFT:
printf( "LEFT!\n" );
break;
case SDLK_RIGHT:
printf( "RIGHT!\n" );
break;
default:
break;
}
}
}
}
SDL_Quit();
return 0;
}
I would like to avoid use SDL_Init(SDL_INIT_VIDEO) without create a SDL_Window using only SDL_Init(SDL_INIT_EVENTS). Actually, my problem is that I only can receive the events if I create the windows and focus it. Is it possible to get the events globally without the focus?
My strategy is to try to use SDL library to isolate OS events behavior and focus in record/play small events provided by an user. Other suggests are welcome.

Executable not running in windows except when using terminal

I'm using the SDL_TFF library and it compiles, but the executable doesn't run directly, except when I run it from the terminal. If I comment out the SDL_TFF code it runs normally.
Does anyone know what could be causing this problem?
Edit:
#include <stdio.h>
#include <SDL.h>
#include <SDL_ttf.h> //version 2.0.12
TTF_Font* Font;
SDL_DisplayMode Desktop_Display_Mode;
SDL_Window* Window;
SDL_Surface* Window_surface;
SDL_Renderer* Renderer;
bool load_font()
{
//Font = TTF_OpenFont("fonts\\NotoSans-Bold.ttf", 16);
Font = TTF_OpenFont("fonts\\NotoSansCJKjp-Bold.otf", 18);
if (Font == NULL)
{
SDL_LogCritical(
SDL_LOG_CATEGORY_APPLICATION,
"Count not load font! TTF_Error: %s\n", TTF_GetError()
);
return false;
}
return true;
}
bool initialize()
{
// Initialize SDL Library
if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
{
SDL_LogCritical(
SDL_LOG_CATEGORY_APPLICATION,
"SDL could not initialize! SDL_Error: %s\n", SDL_GetError()
);
return false;
}
// Initialize SDL_ttf library
if (TTF_Init() != 0)
{
SDL_LogCritical(
SDL_LOG_CATEGORY_APPLICATION,
"SDL_ttf could not initialize! TTF_Error: %s\n", TTF_GetError()
);
return false;
}
// Load Font ---------------------------------------------------------------
if ( !load_font() )
{
return false;
}
// Get Desktop Display Mode
if (SDL_GetDesktopDisplayMode(0, &Desktop_Display_Mode) != 0)
{
SDL_LogCritical(
SDL_LOG_CATEGORY_APPLICATION,
"SDL could not get Desktop Display Mode! SDL_Error: %s\n",
SDL_GetError()
);
return false;
}
// Create Window
Window = SDL_CreateWindow(
"SDL Test",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
Desktop_Display_Mode.w, Desktop_Display_Mode.h,
SDL_WINDOW_BORDERLESS //Flags
);
if( Window == NULL )
{
SDL_LogCritical(
SDL_LOG_CATEGORY_APPLICATION,
"Window could not be created! SDL_Error: %s\n",
SDL_GetError()
);
return false;
}
Renderer = SDL_CreateRenderer( Window, -1,
SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC
);
if ( Renderer == NULL )
{
SDL_LogCritical(
SDL_LOG_CATEGORY_APPLICATION,
"Renderer could not be created! SDL_Error: %s\n",
SDL_GetError()
);
return false;
}
return true;
}
bool clear_screen()
{
if ( SDL_SetRenderDrawColor( Renderer, 0x00, 0x00, 0x00, 0xFF ) != 0 )
{
SDL_LogCritical(
SDL_LOG_CATEGORY_APPLICATION,
"Could not set render draw color! SDL_Error: %s\n",
SDL_GetError()
);
return false;
}
if ( SDL_RenderClear( Renderer ) != 0 )
{
SDL_LogCritical(
SDL_LOG_CATEGORY_APPLICATION,
"Could not clear the renderer! SDL_Error: %s\n",
SDL_GetError()
);
return false;
}
return true;
}
int main( int argc, char* args[] )
{
SDL_Log("Started.");
bool running = initialize();
SDL_Color text_color = {255, 255, 255};
const char* text_string;
text_string = "A journey of a thousand miles begins with a single step.\n こんにちは";
SDL_Rect text_dest;
text_dest.x = 100;
text_dest.y = 100;
text_dest.w = 0;
text_dest.h = 0;
if ( TTF_SizeUTF8(Font, text_string, &text_dest.w, &text_dest.h) != 0)
{
SDL_LogCritical(
SDL_LOG_CATEGORY_APPLICATION,
"Unable to get text size! TTF_Error: %s\n", TTF_GetError()
);
running = false;
}
SDL_Surface* text_surface = NULL;
text_surface = TTF_RenderUTF8_Solid(
Font,
text_string,
text_color
);
if ( text_surface == NULL )
{
SDL_LogCritical(
SDL_LOG_CATEGORY_APPLICATION,
"Unable to render text! SDL_Error: %s\n",
TTF_GetError()
);
running = false;
}
SDL_Texture* text_texture = NULL;
text_texture = SDL_CreateTextureFromSurface( Renderer, text_surface );
if ( text_texture == NULL )
{
SDL_LogCritical(
SDL_LOG_CATEGORY_APPLICATION,
"Unable to render text! SDL_Error: %s\n",
TTF_GetError()
);
running = false;
}
// MAIN LOOP ===============================================================
SDL_Event event;
while (running)
{
// Clear the screen
if ( !clear_screen() )
{
break;
}
// Check for events
if (SDL_PollEvent( &event))
{
// Check for the quit event
if (event.type == SDL_QUIT)
{
SDL_Log("Quit.");
break;
}
}
// Apply the text
if ( SDL_RenderCopy( Renderer, text_texture, NULL, &text_dest ) != 0 )
{
SDL_LogCritical(
SDL_LOG_CATEGORY_APPLICATION,
"Unable to draw text! SDL_Error: %s\n",
SDL_GetError()
);
break;
}
//Update Window
SDL_RenderPresent( Renderer );
}
//Destroy Window
SDL_DestroyWindow( Window );
SDL_DestroyRenderer( Renderer);
//Quit SDL subsystems
TTF_Quit();
SDL_Quit();
SDL_Log("Ended.");
return 0;
}
Edit2: I tested more thorougly and it seems that the function TTF_OpenFont() is causing the problem. As long as I don't call that function the exe will run normally.
SOLVED!
It was the way I was executing the program from command line: "\bin\myprog.exe"
Thus the relative filepath was incorrect because "\bin\fonts..." did not exist. As I have not implemented SDL_LogSetOutputFunction to write logs to a file and std out is apparently suppressed I could not see that I must have been getting error messages indicating that the file was not being loaded.

boost::io_service run() never returns sometimes

I have the following code to read data from a RS232 port. For some (from beginning) runs, io.run() returns immediately and m_handler() is called which is expected. but sometimes (a fresh run from beginning), io.run() goes into a inside forever loop(stacked inside forever) even for the first time called inside the while loop. And this happens randomly. What's is/are the potential problem(s) at here?
#define BUF_SIZE 512
char data[BUF_SIZE];
void my_handler(const boost::system::error_code& err, std::size_t bytes_transferred)
{
printf("%d\n", bytes_transferred);
if (!err){
process_data();
}
}
void test_serial_port( int argc, char* argv[] )
{
// hard coded parameters
const char *PORT = "COM1";
serial_port_base::baud_rate BAUD(9600);
serial_port_base::character_size CSIZE( 8 );
serial_port_base::flow_control FLOW( serial_port_base::flow_control::software );
serial_port_base::parity PARITY( serial_port_base::parity::none );
serial_port_base::stop_bits STOP( serial_port_base::stop_bits::one );
io_service io;
serial_port port( io, PORT );
// go through and set all the options as we need them
// all of them are listed, but the default values work for most cases
port.set_option( BAUD );
port.set_option( CSIZE );
port.set_option( FLOW );
port.set_option( PARITY );
port.set_option( STOP );
while( !kbhit() )
{
io.reset();
port.async_read_some(
boost::asio::buffer(data, BUF_SIZE),
boost::bind(&my_handler, boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred )
);
io.run();
Sleep(300);
}
}

Why does DebugActiveProcessStop crash my debugging app?

I have a debugging program which I've written to attach to a process and create a crash dump file. That part works fine.
The problem I have is that when the debugger program terminates, so does the program that it was debugging.
I did some Googling and found the DebugActiveProcessStop() API call. This didn't show up in my older MSDN documentation as it was only introduced in Windows XP so I've tried loading it dynamicall from Kernel32.dll at runtime.
Now my problem is that my debugger program crashes as soon as the _DebugActiveProcessStop() call is made. Can somebody please tell me what I'm doing wrong?
typedef BOOL (*DEBUGACTIVEPROCESSSTOP)(DWORD);
DEBUGACTIVEPROCESSSTOP _DebugActiveProcessStop;
HMODULE hK32 = LoadLibrary( "kernel32.dll" );
if( hK32 )
_DebugActiveProcessStop = (DEBUGACTIVEPROCESSSTOP) GetProcAddress( hK32,"DebugActiveProcessStop" );
else
{
printf( "Can't load Kernel32.dll\n" );
return;
}
if( ! _DebugActiveProcessStop )
{
printf( "Can't find DebugActiveProcessStop\n" );
return;
}
...
void DebugLoop( void )
{
DEBUG_EVENT de;
while( 1 )
{
WaitForDebugEvent( &de, INFINITE );
switch( de.dwDebugEventCode )
{
case CREATE_PROCESS_DEBUG_EVENT:
hProcess = de.u.CreateProcessInfo.hProcess;
break;
case EXCEPTION_DEBUG_EVENT:
// PDS: I want a crash dump immediately!
dwProcessId = de.dwProcessId;
dwThreadId = de.dwThreadId;
WriteCrashDump( &de.u.Exception );
return;
case CREATE_THREAD_DEBUG_EVENT:
case OUTPUT_DEBUG_STRING_EVENT:
case EXIT_THREAD_DEBUG_EVENT:
case EXIT_PROCESS_DEBUG_EVENT :
case LOAD_DLL_DEBUG_EVENT:
case UNLOAD_DLL_DEBUG_EVENT:
case RIP_EVENT:
default:
break;
}
ContinueDebugEvent( de.dwProcessId, de.dwThreadId, DBG_CONTINUE );
}
}
...
void main( void )
{
...
BOOL bo = DebugActiveProcess( dwProcessId );
if( bo == 0 )
printf( "DebugActiveProcess failed, GetLastError: %u \n",GetLastError() );
hProcess = OpenProcess( PROCESS_ALL_ACCESS, TRUE, dwProcessId );
if( hProcess == NULL )
printf( "OpenProcess failed, GetLastError: %u \n",GetLastError() );
DebugLoop();
_DebugActiveProcessStop( dwProcessId );
CloseHandle( hProcess );
}
The reason its crashing is because I missed out the WINAPI keyword on my function pointer definitions.
This works:
typedef BOOL (WINAPI *DEBUGSETPROCESSKILLONEXIT)(BOOL);

C++ Win32, How to add a dropdown menu to a Win32 DialogBox

C++ Win32, How to add a dropdown menu to a Win32 DialogBox
Hi,
This is my first time posting quesiton to stackoverflow.
I am trying to add combobox (in menu.cpp) to a Win32 Dialogbox (in fingerspell.cpp). I am not very fluent in Win32
programming and most of the msdn example snippets draw a combobox inside a window. Even though Dialogbox is technically
a window but I haven't had much progress in modifing any window example code to handle a DialogBox. I would really appreciate a working example.
A rough sketch of the code is as follows. fingerspell.cpp creates implements the WinMain function and then calls up
other custom classes to draw inside this DialogBox. No other window controls, like buttons, text area etc, are used.
code for fingerspell.cpp is
#include "fingerspell.h"
extern "C" __declspec(dllexport)bool isGloveDriverInstalled();
extern "C" __declspec(dllimport)bool initialize();
#define RUN( x ) if ( SUCCEEDED( result ) ) { result = x; }
BOOL g_fullscreen = FALSE;
bool portReady;
INT_PTR CALLBACK OptionDialogProc( HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg) {
case WM_INITDIALOG:
if (wParam == IDOK)
return TRUE ;
else
return FALSE ;
break;
case WM_COMMAND:
if (HIWORD(wParam) == BN_CLICKED) {
if (LOWORD(wParam) == IDOK) {
g_fullscreen = TRUE;
EndDialog (hwndDlg, 1) ;
}
else if (LOWORD(wParam) == ID_WINDOW_OPT) {
g_fullscreen = FALSE;
EndDialog (hwndDlg, 1) ;
}
else {
EndDialog (hwndDlg, 0) ;
}
return TRUE ;
}
default:
return FALSE;
break ;
}
}
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
INT_PTR DispOption = DialogBox (hInstance, MAKEINTRESOURCE(IDD_DISPLAY_OPTIONS), NULL, OptionDialogProc) ;
if (DispOption == 0)
return 0 ;
//srand( GetTickCount( ) );
HRESULT result = S_OK;
if (!isGloveDriverInstalled())
{
portReady = FALSE;
MessageBox(NULL, "The Glove Driver is not istalled ", "Error", MB_OK );
}
else
{
if (!initialize())
{
portReady = FALSE;
MessageBox(NULL, "Error Opening Com Port", "Error", MB_OK );
}
else
{
portReady = TRUE;
}
}
RUN( Words ::Create ( "default.txt" ) );
RUN( Window::Create ( ) );
RUN( Render::Create ( ) );
RUN( Art ::Create ( ) );
RUN( Menu ::Create ( ) );
RUN( Window::MessageLoop( ) );
RUN( Menu ::Destroy ( ) );
RUN( Art ::Destroy ( ) );
RUN( Render::Destroy ( ) );
RUN( Window::Destroy ( ) );
RUN( Words ::Destroy ( ) );
if ( FAILED( result ) )
{
MessageBox( GetDesktopWindow( ), "Warning - Fail Code Detected", "Fingerspell 2002", MB_ICONWARNING | MB_OK );
}
return result;
}
code for menu.cpp. file where im trying to add combobox.
#include "fingerspell.h"
#include <windows.h> //include all the basics
#include <tchar.h> //string and other mapping macros
#include <string>
HRESULT Menu::Create( )
{
// set menu as the background
Render::SetBackground( ART_MENU );
// clear overlay
Render::Reset( );
Window::SetProc( Proc );
return S_OK;
}
HRESULT Menu::Destroy( void )
{
return S_OK;
}
LRESULT CALLBACK Menu::Proc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
DWORD i ;
const static RECT button_rect[ 8 ] =
{
{ 52, 139, 52 + 101, 139 + 50 }, //1. about
{ 55, 212, 55 + 85, 212 + 50 }, // 2. learn
{ 67, 280, 67 + 63, 280 + 50 }, // 3. exit
{ 397, 137, 397+ 233, 137 + 50 }, // 4. Add Delete List.
{ 421, 187, 421+ 183, 187 + 50 }, // 5. add word
{ 413, 247, 413+ 201, 247 + 50 }, // 6. delete word
{ 450, 300, 450+ 124, 300 + 50 }, // 7. practice
{ 473, 349, 473 + 82, 349 + 50 }, // 8. test
};
// custom message processing
switch ( uMsg )
{
case WM_CREATE:
return OnCreate(hwnd,reinterpret_cast<CREATESTRUCT*>(lParam));
case WM_MOUSEMOVE: // move is moved, see where is it pointing to.
{
int xPos = GET_X_LPARAM( lParam );
int yPos = GET_Y_LPARAM( lParam );
for ( i = 0; i < 8; i++ )
{
if ( xPos >= button_rect[ i ].left && yPos >= button_rect[ i ].top )
{
if ( xPos < button_rect[ i ].right && yPos < button_rect[ i ].bottom )
{
// set selection
Render::SetOverlay( 0, (ART) ( ART_MENU_LEARN + i ), button_rect[ i ].left, button_rect[ i ].top );
break;
}
}
}
if ( i == 8 )
{
//remove selection
Render::SetOverlay( 0, ART_NULL, 0, 0 );
}
return 0;
}
case WM_LBUTTONDOWN:
{
switch ( Render::GetOverlay( 0 ) )
{
case ART_MENU_EXIT: // done.
{
Menu::Destroy( );
Learn::Create( );
break;
}
case ART_MENU_LEARN: // done
{
Menu::Destroy( );
About::Create( );
break;
}
case ART_MENU_ABOUT: // done
{
Menu::Destroy( );
Test::Create( );
break;
}
case ART_MENU_TEST: // done.
{
Menu::Destroy( );
Practice::Create( );
break;
}
case ART_MENU_DELETEWORD: // done
{
Menu::Destroy( );
AddWord::Create( );
break;
}
case ART_MENU_ADDDELETELIST:
{
//Menu::Destroy () ;
PostQuitMessage( 0 );
break;
}
case ART_MENU_ADD:
{
Menu::Destroy( );
// About is place holder. should be AddDELETELIST
About::Create( );
break;
}
case ART_MENU_PRACTICE: // done.
{
Menu::Destroy( );
// About is place holder. shd be DELETEWORD.
About::Create( );
break;
}
}
return 0;
}
}
// default message processing
return DefWindowProc( hwnd, uMsg, wParam, lParam );
}
Thanks.
http://www.resedit.net/
I think it's better than visual studio editor (that comes only with professional)
On Vista or later, use a simple BS_SPLITBUTTON style of button control (WC_BUTTON), and then handle BCN_DROPDOWN to create your menu.
I haven't tried this actual code, but this sample looks reasonable: http://www.codereflect.com/2009/02/19/how-to-create-a-drop-down-button-in-windows-vista-7/
Martyn

Resources