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


 

 

 

 

 

1.MFC下調用控制台

在CWinApp的InitInstance中對話框的DoModal之前加入

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

在CWinApp的ExitInstance中加入

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

 

由於直接關閉控制台會出錯,所以禁用關閉。

在對話框的OnInitDialog中

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);      //移除關閉

 

 

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

(1)直接printf或cout

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

 


(2)

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

 

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

2.在右邊MFC的使用中選擇“在共享 DLL 中使用 MFC”

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  }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM