效果
代码
MyLogWindow
头文件
#ifndef _MY_LOG_WINDOW_H_
#define _MY_LOG_WINDOW_H_
#include <wx/textctrl.h>
#include <wx/frame.h>
#include <wx/filename.h>
#define LOG_INFO(msg) wxLogMessage(wxT("[%s][%s:%u] - %s"), wxFileName::FileName(__TFILE__).GetFullName(), wxString::FromAscii(__WXFUNCTION__).c_str(), __LINE__, msg);
#define LOG_WARN(msg) wxLogWarning(wxT("[%s][%s:%u] - %s"), wxFileName::FileName(__TFILE__).GetFullName(), wxString::FromAscii(__WXFUNCTION__).c_str(), __LINE__, msg);
#define LOG_ERROR(msg) wxLogError(wxT("[%s][%s:%u] - %s"), wxFileName::FileName(__TFILE__).GetFullName(), wxString::FromAscii(__WXFUNCTION__).c_str(), __LINE__, msg);
class MyLogWindow : public wxFrame
{
public:
MyLogWindow(wxFrame* parent);
private:
wxTextCtrl* m_textCtrl;
};
#endif // !_MY_LOG_WINDOW_H_
cpp文件
#include <wx/panel.h>
#include <wx/sizer.h>
#include <wx/log.h>
#include <wx/app.h>
#include "MyLogWindow.h"
MyLogWindow::MyLogWindow(wxFrame* parent)
: wxFrame(parent, wxID_ANY, "My Log Window")
{
wxPanel* panel = new wxPanel(this);
// 创建一个垂直盒子Sizer
wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL);
// 添加日志文本控件
m_textCtrl = new wxTextCtrl(panel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE | wxTE_READONLY);
vbox->Add(m_textCtrl, wxSizerFlags().Proportion(1).Expand().Border(wxALL, 5));
// 设置Sizer
panel->SetSizerAndFit(vbox);
// 设置窗口大小和位置
SetSize(wxSize(860, 400));
Centre();
// 将日志写入文本控件
wxLog::SetActiveTarget(new wxLogTextCtrl(m_textCtrl));
// wxLogMessage(wxT("[%s/%s/%u] '%s' is starting"), __TFILE__, wxString::FromAscii(__WXFUNCTION__).c_str(), __LINE__, wxTheApp->GetAppName().c_str());
LOG_INFO(wxString::Format("'%s' is staring", wxTheApp->GetAppName().c_str()));
// wxLogVerbose(wxT("[%s/%s/%u] Verbose Logging Enabled"), __TFILE__, wxString::FromAscii(__WXFUNCTION__).c_str(), __LINE__);
}
使用
// 在 MyApp 的 OnInit 中将日志窗口的父窗口设置为主窗口, 这样主窗口退出的时候日志窗口也会退出, 应用程序结束
bool MyApp::OnInit()
{
MyFrame* frame = new MyFrame();
MyLogWindow* log_window_m = new MyLogWindow(frame);
log_window_m->Show(true);
// MyFrame* frame = new MyFrame();
frame->SetSize(wxSize(800,600));
frame->Center();
frame->Show(true);
return true;
}
// 可以使用宏, 包含了文件名(不带路径), 方法, 行号
void MyFrame::OnHello(wxCommandEvent& event)
{
LOG_INFO("Hello world from wxWidgets!");
}