如何在Visual Studio 2010中查看Win32应用程序(使用WinMaininput)中的printf输出?
严格回答你的问题,你可以使用winbase.h OutputDebugString
函数在Visual Studio 2010中的Win32应用程序中使用类似printf的函数。
我写了一个简单的程序,显示如何做到这一点。
#include <windows.h> #include <stdio.h> int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdShow, int nCmdShow) { int number = 10; char str[256]; sprintf_s(str, "It works! - number: %d \n", number); OutputDebugString(str); return 0; }
OutputDebugString
函数将LPCSTR
作为参数。 打印前,我使用sprintf_s
来格式化字符串。
这会将结果打印到Visual Studio 2010输出窗口。
我希望它有帮助!
我知道我在过去使用AllocConsole函数完成了这个工作,但是我也记得它比我想象的要复杂一点。
在AllocConsole上进行快速的Google搜索就可以看出显然是Windows Developer Journal的文章 ,看起来相关。 从那里,以下似乎类似于我记得,它是模糊的。
void SetStdOutToNewConsole() { int hConHandle; long lStdHandle; FILE *fp; // Allocate a console for this app AllocConsole(); // Redirect unbuffered STDOUT to the console lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE); hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); fp = _fdopen(hConHandle, "w"); *stdout = *fp; setvbuf(stdout, NULL, _IONBF, 0); }
你需要一个控制台窗口。 到目前为止,最简单的方法是更改链接器选项:项目+属性,链接器,系统,子系统=控制台。 添加一个main()方法:
int main() { return _tWinMain(GetmoduleeHandle(NULL), NULL, GetCommandLine(), SW_SHOW); }
谢谢你的答案。 这对我帮助很大。
我需要一个更大的回滚缓冲区,所以在看了一下API函数之后做了一些补充。 在这里共享以防别人帮助其他人:
void SetStdOutToNewConsole() { // allocate a console for this app AllocConsole(); // redirect unbuffered STDOUT to the console HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE); int fileDescriptor = _open_osfhandle((intptr_t)consoleHandle, _O_TEXT); FILE *fp = _fdopen( fileDescriptor, "w" ); *stdout = *fp; setvbuf( stdout, NULL, _IONBF, 0 ); // give the console window a nicer title SetConsoleTitle(L"Debug Output"); // give the console window a bigger buffer size CONSOLE_SCREEN_BUFFER_INFO csbi; if ( GetConsoleScreenBufferInfo(consoleHandle, &csbi) ) { COORD bufferSize; bufferSize.X = csbi.dwSize.X; bufferSize.Y = 9999; SetConsoleScreenBufferSize(consoleHandle, bufferSize); } }
这将回滚(屏幕缓冲区)高度增加到9999行。
在Windows XP和Windows 7上测试。
另一种不需要改变现有的printf,也可以打印到VS输出窗口的方法是这样的:
#define printf printf2 int __cdecl printf2(const char *format, ...) { char str[1024]; va_list argptr; va_start(argptr, format); int ret = vsnprintf(str, sizeof(str), format, argptr); va_end(argptr); OutputDebugStringA(str); return ret; } ... printf("remains %s", "the same");
这里是一个页面,告诉你如何做到这一点,包括示例代码。
您必须使用AllocConsole()创建控制台窗口,然后将C标准文件句柄与新控制台窗口的句柄相关联。