Visual C++ 7.1Visual C++ 8.0Visual Studio 6Visual C++ 7.0Windows 2003Windows 2000Visual C++ 6.0Windows XP中级开发Visual StudioWindowsC++
替换 MFC 使用的 printf






2.53/5 (12投票s)
2004年11月26日

34816
用 MFC 替换 printf。
引言
本文介绍了一种简单的方法,用于替换 MFC 应用程序中的 printf
函数调用。
背景
我们经常会发现非常有用的、写得很好的代码,其中包含大量的 printf
函数调用。 当我们将此代码移植到基于 MFC 的 GUI 应用程序时,我们肯定希望 printf
的输出显示在列表框或消息框中。 将 printf
替换为消息框或列表框显示只需要几行代码。 如果有成百上千个 printf
语句,这将会非常困难。
使用代码
用 MFC_Printf
一次性替换所有 printf
调用会很好,只需按 Ctrl+H 快捷键,即查找和替换即可。 以下是 MFC_Printf(....)
的构造方式
class CMFCLog { { public: CMFCLog(); { } ~CMFCLog(); { } CListBox *m_pLB; // pointer to a CListBox void MFC_Printf(const char *formatstring,...) { CString Str, s2; va_list args; va_start(args, str); Str.FormatV(formatstring, args); Str.Replace('\n',' '); // Assuming that m_pLB is already initialized. m_pLB->AddString(Str); // We can even call a MessageBox here... } };
// This code is within the CPP file which contain lots of printf static CMFCLog Log; ....... Assign the m_pLB some where before calling MFC_Printf // printf("\n\nThe Counter Values is: %d",i); is replaced with Log.MFC_Printf("\n\nThe Counter Values is: %d", i);
关注点
我们应该始终寻找简单的解决方案。