MFC下調用控制檯和控制檯下MFC庫的支持

 

 

 

 

 

1.MFC下調用控制檯ios

在CWinApp的InitInstance中對話框的DoModal以前加入測試

1 AllocConsole();                                          // 開闢控制檯
2 SetConsoleTitle(_T("測試窗口"));                  // 設置控制檯窗口標題
3 freopen("CONOUT$","w",stdout);                // 重定向輸出
4 freopen( "CONIN$", "r+t", stdin );              // 申請讀

在CWinApp的ExitInstance中加入spa

1 FreeConsole();//釋放控制檯

 

因爲直接關閉控制檯會出錯,因此禁用關閉。code

在對話框的OnInitDialog中component

1 char   szBuf[100]; 
2 GetConsoleTitle(szBuf,   100);                 //獲得控制檯標題
3 HWND   hwnd   =   ::FindWindow(NULL,   szBuf);      //查找控制檯 
4 HMENU   hmenu   =   ::GetSystemMenu(hwnd,   FALSE);   //獲取菜單
5 ::RemoveMenu(hmenu,   SC_CLOSE,MF_BYCOMMAND);      //移除關閉

 

 

下面是向控制檯寫的方法,兩種:blog

(1)直接printf或coutci

1 printf("Hello World!\n"); // 寫數據

 


(2)it

1 HANDLE   outPut; 
2 outPut   =   GetStdHandle(STD_OUTPUT_HANDLE); 
4 WriteConsole(outPut,"Hello World!\n", strlen("Hello World!\n"),NULL,NULL);

 

2.如何在控制檯程序下添加MFC庫的支持
1.單擊菜單欄的項目->屬性->配置屬性io

2.在右邊MFC的使用中選擇「在共享 DLL 中使用 MFC」class

3.新建一個stdafx.h頭文件,並在裏面加入以下代碼

 1 #define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS      // some CString constructors will be explicit
 2  
 3  #ifndef VC_EXTRALEAN
 4  #define VC_EXTRALEAN            // Exclude rarely-used stuff from Windows headers
 5  #endif
 6  
 7  #include <afx.h>
 8  #include <afxwin.h>         // MFC core and standard components
 9  #include <afxext.h>         // MFC extensions
10  #ifndef _AFX_NO_OLE_SUPPORT
11  #include <afxdtctl.h>           // MFC support for Internet Explorer 4 Common Controls
12  #endif
13  #ifndef _AFX_NO_AFXCMN_SUPPORT
14  #include <afxcmn.h>                     // MFC support for Windows Common Controls
15  #endif // _AFX_NO_AFXCMN_SUPPORT
16  
17  #include <iostream>

 


4.在cpp文件中包含該頭文件#include "stdafx.h"

5.實例:

 1 #include "stdafx.h"
 2  using namespace std;
 3  int main(void)
 4  {
 5      CString str("Hello World");
 6      AfxMessageBox(str);
 7      USES_CONVERSION;
 8      char * pstr = T2A(str);
 9      cout << pstr;
10  }
相關文章
相關標籤/搜索