A Win32 Console Class
Breakpoint debugging is not necessarily the most appropriate debugging method for the preparation of the Win32 program, especially for a high-real-time program such as games. Many times, we're more eager to see debugging information printed in real time.
One method is to export information to the VC debug console using the commissioning function Output DebugString() of VC. Another method is to create a window program based on the Win32 console project (the portal is Main rather than WinMain). Macro can be used to control the compilation, so that the Debug version has a console, and the Releaase version does not have a console, like this:
// 一个简单的方法
#ifndef _DEBUG
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
#else
int main(int argc, char** argv) {
#endif//_DEBUG
But this method is not flexible, and here is a way to get the console directly using Win32 API. Everything is in the code:
// DbgCon.h
#ifndef DBGCON_H
#define DBGCON_H
#include <windows.h>;
#include <stdio.h>;
class DbgCon {
public:
DbgCon();
~DbgCon();
void Show();
void Hide();
void Top();
void NoTop();
private:
HWND HWnd_;
FILE* ConIn_;
FILE* ConOut_;
};
#endif//DBGCON_H
// DbgCon.cpp
#include "DbgCon.h"
DbgCon::DbgCon()
: HWnd_(0)
, ConIn_(0)
, ConOut_(0) {
// 申请一个控制台
if( AllocConsole() ) {
HWnd_ = GetConsoleWindow();
// 把管道转入该控制台
freopen_s(&ConIn_, "CONIN$", "r+t", stdin);
freopen_s(&ConOut_, "CONOUT$", "w+t", stdout);
// 去掉控制台窗口上的关闭功能
//(控制台窗口上的关闭操作会关掉整个进程)
HMENU HMenu = GetSystemMenu(HWnd_, FALSE);
RemoveMenu(HMenu, SC_CLOSE, MF_BYCOMMAND);
}
}
DbgCon::~DbgCon() {
FreeConsole();
if( ConOut_ ) {
fclose(ConOut_);
}
if( ConIn_ ) {
fclose(ConIn_);
}
}
void DbgCon::Show() {
// 显示控制台窗口(恢复到正常状态)
ShowWindow(HWnd_, SW_SHOWNORMAL);
}
void DbgCon::Hide() {
// 隐藏控制台窗口
ShowWindow(HWnd_, SW_HIDE);
}
void DbgCon::Top() {
// 置顶控制台窗口
SetWindowPos(HWnd_, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE||SWP_NOSIZE);
}
void DbgCon::NoTop() {
// 取消置顶
SetWindowPos(HWnd_, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE||SWP_NOSIZE);
}