如何在win32控制台加入MFC对话框(Adding Windows To Your Console Application)

     控制台程序与window程序最大的区别在于前面没有消息循环机制,而后者有。我一直在想如何才能在控制台应用程序中添加一个对话框,也许有时你需要在控制台弹出一个对话框让用户输入一些文本信息或者在下拉框中选择一项信息,也许这篇文章在实际用过程中有什么明显的用途。

      现在我们以“Hello,world”为例来说明。我们在Main()函数中通过_beginthread API 创建一个线程,在线程中,创建一个简单的对话框(对话框资源文件可能由其它MFC程序生成后,将文件复制到当前程序目录下,并自行添加到工程中,这是我自己理解。)

 

代码如下:

// define _MT so that _beginthread( ) is available #ifndef _MT #define _MT #endif #include "stdio.h" #include "windows.h" #include "process.h" #include "resource.h" // global flag bool bDone = false; // this function is called by a new thread void InputThreadProc( void *dummy ) { // create the dialog window HWNDhWnd = ::CreateDialog(NULL, MAKEINTRESOURCE(IDD_DIALOG),NULL,NULL); if ( hWnd!=NULL ) { // show dialog ::ShowWindow(hWnd,SW_SHOW); } else { printf("Failed to create dialog/n"); bDone = true; return; } // message loop to process user input MSG msg; while(1) { if ( ::PeekMessage(&msg, hWnd, 0, 0, PM_REMOVE) ) { if ( msg.message==WM_KEYUP ) { int nVirtKey = (int) msg.wParam; // if the user pressed the ESCAPE key, then // print the text the user entered and quit if ( nVirtKey==VK_ESCAPE ) { // get the edit control HWND hEdit = ::GetDlgItem(hWnd,IDC_EDIT); if ( hEdit ) { // get the input text the user entered // and print it to the console window char pText[3201]; int nSize = ::GetWindowText( hEdit, pText, 3200 ); pText[nSize] = 0; printf("/nYou have entered the "); printf("following text in a second "); printf("thread:/n/n%s/n/n",pText); } else { printf("Failed to get edit control/n"); } // destroy the dialog and get out of // the message loop ::DestroyWindow(hWnd); bDone = true; break; } } // process message ::TranslateMessage(&msg); ::DispatchMessage(&msg); } else { // if there is no message to process, // then sleep for a while to avoid burning // too much CPU cycles ::Sleep(100); } } } void main( int argc, char** argv ) { printf("Hello, world of console apps/n"); // create a new thread to allow user input if( _beginthread(InputThreadProc, 0, NULL )==-1) { printf("Failed to create thread"); return; } // wait for the new thread to finish while ( !bDone ) { // sleep 3 seonds ::Sleep(3000); printf("main thread running/n"); } } /************************** end ************************/

 

原文出处:http://www.codeproject.com/KB/winsdk/winconsole.aspx 

翻译过程中,将主要的思想翻译过来。

你可能感兴趣的:(thread,windows,null,application,mfc,dialog)