Nic*_*unt 19 c windows visual-studio
如何在Visual Studio 2010中查看Win32应用程序(使用WinMain输入)中的printf输出?
rbe*_*nto 28
严格回答您的问题,您可以使用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;
}
Run Code Online (Sandbox Code Playgroud)
该OutputDebugString
函数将a LPCSTR
作为参数.我sprintf_s
在打印之前用它来格式化字符串.
这会将结果打印到Visual Studio 2010输出窗口.
我希望它有所帮助!
tor*_*rak 14
我知道我过去使用AllocConsole功能完成了这项工作,但我还记得它比我想象的要复杂一些.
在AllocConsole上进行快速Google搜索会产生一些看似相关的Windows开发者期刊文章.从那里,以下似乎与我记得的相似,模糊不清.
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);
}
Run Code Online (Sandbox Code Playgroud)
Han*_*ant 14
你需要一个控制台窗口.到目前为止,最简单的方法是更改链接器选项:Project + Properties,Linker,System,SubSystem = Console.添加main()方法:
int main() {
return _tWinMain(GetModuleHandle(NULL), NULL, GetCommandLine(), SW_SHOW);
}
Run Code Online (Sandbox Code Playgroud)
感谢torak的回答.这对我帮助很大.
我需要一个更大的回滚缓冲区,所以在看了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);
}
}
Run Code Online (Sandbox Code Playgroud)
这会将回滚(屏幕缓冲区)高度增加到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");
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
55661 次 |
最近记录: |