Win32项目和Win32控制台应用程序有点不同,没有控制台窗口,有时做调试需要用断点。不过也可以有,在cpp文件头加上这句话#pragma comment( linker, "/subsystem:\"console\" /entry:\"WinMainCRTStartup\""),就可以开启控制台窗口,也就可以使用printf来查看观察变量或者调试了。除此之外,还有其它方式来输出想要的信息
1. 使用OutputDebugString。用个简单的代码作为例子
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nShowCmd) {
char test[25] = "test\n";
//wsprintf(test, "%s%d", test, 10); //可能需要在属性里设置字符集
OutputDebugString(test);
//system("pause"); //没有这句话,输出的信息可能比较难找
}
使用system("pause")的话,可以在调试信息最末尾找到输出的信息。在字符串后加上'\n'能够起到换行效果,可以用wsprintf来控制输出格式。OutputDebugString输出的长度有限,具体多长没试。OutputDebugString支持的格式不只有字符串数组,还有LPSTR等其它类型。
2.使用cmd打印信息。在c/c++使用cmd也就是使用system()方法。不过打印信息也需要配合system("pause")暂停一下程序。看下面的例子。
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nShowCmd) {
char test[50] = "test";
char out[50];
wsprintf(out, "echo %s & pause", test);
system(out);
}
这种做法有局限性,首先test不能有换行符,就像在cmd输入命令一样,输入换行就是执行命令了。其次,需要和pause用&连接起来,不然结果就是一闪而过。当然,除了echo,还可以使用其它的cmd命令。
3.使用TextOut,DrawText,MessageBox等方法,前两个方法要在Win32应用程序窗口才能显示出来,而MessageBox则是弹出一个小窗口。前两个方法只是用来调试感觉就有点大材小用了。