1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: exec sample demonstrates wxExecute and related functions
4 // Author: Vadim Zeitlin
8 // Copyright: (c) Vadim Zeitlin
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
21 #pragma implementation "exec.cpp"
22 #pragma interface "exec.cpp"
25 // For compilers that support precompilation, includes "wx/wx.h".
26 #include "wx/wxprec.h"
32 // for all others, include the necessary headers (this file is usually all you
33 // need because it includes almost all "standard" wxWindows headers
39 #include "wx/msgdlg.h"
40 #include "wx/textdlg.h"
41 #include "wx/listbox.h"
44 #include "wx/txtstrm.h"
46 #include "wx/process.h"
52 // ----------------------------------------------------------------------------
54 // ----------------------------------------------------------------------------
56 // Define a new application type, each program should derive a class from wxApp
57 class MyApp
: public wxApp
60 // override base class virtuals
61 // ----------------------------
63 // this one is called on application startup and is a good place for the app
64 // initialization (doing it here and not in the ctor allows to have an error
65 // return: if OnInit() returns false, the application terminates)
66 virtual bool OnInit();
69 // Define an array of process pointers used by MyFrame
71 WX_DEFINE_ARRAY(MyPipedProcess
*, MyProcessesArray
);
73 // Define a new frame type: this is going to be our main frame
74 class MyFrame
: public wxFrame
78 MyFrame(const wxString
& title
, const wxPoint
& pos
, const wxSize
& size
);
80 // event handlers (these functions should _not_ be virtual)
81 void OnQuit(wxCommandEvent
& event
);
83 void OnClear(wxCommandEvent
& event
);
85 void OnSyncExec(wxCommandEvent
& event
);
86 void OnAsyncExec(wxCommandEvent
& event
);
87 void OnShell(wxCommandEvent
& event
);
88 void OnExecWithRedirect(wxCommandEvent
& event
);
89 void OnDDEExec(wxCommandEvent
& event
);
91 void OnAbout(wxCommandEvent
& event
);
93 // polling output of async processes
94 void OnIdle(wxIdleEvent
& event
);
97 void OnProcessTerminated(MyPipedProcess
*process
)
98 { m_running
.Remove(process
); }
99 wxListBox
*GetLogListBox() const { return m_lbox
; }
106 MyProcessesArray m_running
;
108 // any class wishing to process wxWindows events must use this macro
109 DECLARE_EVENT_TABLE()
112 // This is the handler for process termination events
113 class MyProcess
: public wxProcess
116 MyProcess(MyFrame
*parent
, const wxString
& cmd
)
117 : wxProcess(parent
), m_cmd(cmd
)
122 // instead of overriding this virtual function we might as well process the
123 // event from it in the frame class - this might be more convenient in some
125 virtual void OnTerminate(int pid
, int status
);
132 // A specialization of MyProcess for redirecting the output
133 class MyPipedProcess
: public MyProcess
136 MyPipedProcess(MyFrame
*parent
, const wxString
& cmd
)
137 : MyProcess(parent
, cmd
)
142 virtual void OnTerminate(int pid
, int status
);
147 // ----------------------------------------------------------------------------
149 // ----------------------------------------------------------------------------
151 // IDs for the controls and the menu commands
165 static const wxChar
*DIALOG_TITLE
= _T("Exec sample");
167 // ----------------------------------------------------------------------------
168 // event tables and other macros for wxWindows
169 // ----------------------------------------------------------------------------
171 // the event tables connect the wxWindows events with the functions (event
172 // handlers) which process them. It can be also done at run-time, but for the
173 // simple menu events like this the static method is much simpler.
174 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
175 EVT_MENU(Exec_Quit
, MyFrame::OnQuit
)
176 EVT_MENU(Exec_ClearLog
, MyFrame::OnClear
)
178 EVT_MENU(Exec_SyncExec
, MyFrame::OnSyncExec
)
179 EVT_MENU(Exec_AsyncExec
, MyFrame::OnAsyncExec
)
180 EVT_MENU(Exec_Shell
, MyFrame::OnShell
)
181 EVT_MENU(Exec_Redirect
, MyFrame::OnExecWithRedirect
)
182 EVT_MENU(Exec_DDEExec
, MyFrame::OnDDEExec
)
184 EVT_MENU(Exec_About
, MyFrame::OnAbout
)
186 EVT_IDLE(MyFrame::OnIdle
)
189 // Create a new application object: this macro will allow wxWindows to create
190 // the application object during program execution (it's better than using a
191 // static object for many reasons) and also declares the accessor function
192 // wxGetApp() which will return the reference of the right type (i.e. MyApp and
196 // ============================================================================
198 // ============================================================================
200 // ----------------------------------------------------------------------------
201 // the application class
202 // ----------------------------------------------------------------------------
204 // `Main program' equivalent: the program execution "starts" here
207 // Create the main application window
208 MyFrame
*frame
= new MyFrame(_T("Exec wxWindows sample"),
209 wxDefaultPosition
, wxSize(500, 140));
211 // Show it and tell the application that it's our main window
215 // success: wxApp::OnRun() will be called which will enter the main message
216 // loop and the application will run. If we returned FALSE here, the
217 // application would exit immediately.
221 // ----------------------------------------------------------------------------
223 // ----------------------------------------------------------------------------
226 MyFrame::MyFrame(const wxString
& title
, const wxPoint
& pos
, const wxSize
& size
)
227 : wxFrame((wxFrame
*)NULL
, -1, title
, pos
, size
)
230 // we need this in order to allow the about menu relocation, since ABOUT is
231 // not the default id of the about menu
232 wxApp::s_macAboutMenuItemId
= Exec_About
;
235 // set the frame icon
237 SetIcon(wxICON(mondrian
));
241 wxMenu
*menuFile
= new wxMenu(_T(""), wxMENU_TEAROFF
);
242 menuFile
->Append(Exec_ClearLog
, _T("&Clear log\tCtrl-C"),
243 _T("Clear the log window"));
244 menuFile
->AppendSeparator();
245 menuFile
->Append(Exec_Quit
, _T("E&xit\tAlt-X"), _T("Quit this program"));
247 wxMenu
*execMenu
= new wxMenu
;
248 execMenu
->Append(Exec_SyncExec
, _T("Sync &execution...\tCtrl-E"),
249 _T("Launch a program and return when it terminates"));
250 execMenu
->Append(Exec_AsyncExec
, _T("&Async execution...\tCtrl-A"),
251 _T("Launch a program and return immediately"));
252 execMenu
->Append(Exec_Shell
, _T("Execute &shell command...\tCtrl-S"),
253 _T("Launch a shell and execute a command in it"));
254 execMenu
->Append(Exec_Redirect
, _T("Capture command &output...\tCtrl-O"),
255 _T("Launch a program and capture its output"));
258 execMenu
->AppendSeparator();
259 execMenu
->Append(Exec_DDEExec
, _T("Execute command via &DDE...\tCtrl-D"));
262 wxMenu
*helpMenu
= new wxMenu(_T(""), wxMENU_TEAROFF
);
263 helpMenu
->Append(Exec_About
, _T("&About...\tF1"), _T("Show about dialog"));
265 // now append the freshly created menu to the menu bar...
266 wxMenuBar
*menuBar
= new wxMenuBar();
267 menuBar
->Append(menuFile
, _T("&File"));
268 menuBar
->Append(execMenu
, _T("&Exec"));
269 menuBar
->Append(helpMenu
, _T("&Help"));
271 // ... and attach this menu bar to the frame
274 // create the listbox in which we will show misc messages as they come
275 m_lbox
= new wxListBox(this, -1);
278 // create a status bar just for fun (by default with 1 pane only)
280 SetStatusText(_T("Welcome to wxWindows exec sample!"));
281 #endif // wxUSE_STATUSBAR
287 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
))
289 // TRUE is to force the frame to close
293 void MyFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
298 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
))
300 wxMessageBox(_T("Exec sample\n© 2000 Vadim Zeitlin"),
301 _T("About Exec"), wxOK
| wxICON_INFORMATION
, this);
304 void MyFrame::OnSyncExec(wxCommandEvent
& WXUNUSED(event
))
306 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
313 wxLogStatus(_T("'%s' is running please wait..."), cmd
.c_str());
315 int code
= wxExecute(cmd
, TRUE
/* sync */);
317 wxLogStatus(_T("Process '%s' terminated with exit code %d."),
322 void MyFrame::OnAsyncExec(wxCommandEvent
& WXUNUSED(event
))
324 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
331 wxProcess
*process
= new MyProcess(this, cmd
);
332 long pid
= wxExecute(cmd
, FALSE
/* async */, process
);
335 wxLogError(_T("Execution of '%s' failed."), cmd
.c_str());
341 wxLogStatus(_T("Process %ld (%s) launched."), pid
, cmd
.c_str());
347 void MyFrame::OnShell(wxCommandEvent
& WXUNUSED(event
))
349 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
356 int code
= wxShell(cmd
);
357 wxLogStatus(_T("Shell command '%s' terminated with exit code %d."),
362 void MyFrame::OnExecWithRedirect(wxCommandEvent
& WXUNUSED(event
))
364 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
372 switch ( wxMessageBox(_T("Execute it synchronously?"),
374 wxYES_NO
| wxCANCEL
| wxICON_QUESTION
, this) )
390 wxArrayString output
;
391 int code
= wxExecute(cmd
, output
);
392 wxLogStatus(_T("command '%s' terminated with exit code %d."),
397 m_lbox
->Append(wxString::Format(_T("--- Output of '%s' ---"),
400 size_t count
= output
.GetCount();
401 for ( size_t n
= 0; n
< count
; n
++ )
403 m_lbox
->Append(output
[n
]);
409 MyPipedProcess
*process
= new MyPipedProcess(this, cmd
);
410 if ( !wxExecute(cmd
, FALSE
/* async */, process
) )
412 wxLogError(_T("Execution of '%s' failed."), cmd
.c_str());
418 m_running
.Add(process
);
425 void MyFrame::OnDDEExec(wxCommandEvent
& WXUNUSED(event
))
428 wxString server
= wxGetTextFromUser(_T("Server to connect to:"),
429 DIALOG_TITLE
, _T("IExplore"));
433 wxString topic
= wxGetTextFromUser(_T("DDE topic:"),
434 DIALOG_TITLE
, _T("WWW_OpenURL"));
438 wxString cmd
= wxGetTextFromUser(_T("DDE command:"),
440 _T("\"file:F:\\wxWindows\\samples\\"
441 "image\\horse.gif\",,-1,,,,,"));
446 wxConnectionBase
*conn
= client
.MakeConnection("", server
, topic
);
449 wxLogError(_T("Failed to connect to the DDE server '%s'."),
454 if ( !conn
->Execute(cmd
) )
456 wxLogError(_T("Failed to execute command '%s' via DDE."),
461 wxLogStatus(_T("Successfully executed DDE command"));
464 #endif // __WINDOWS__
468 void MyFrame::OnIdle(wxIdleEvent
& event
)
470 size_t count
= m_running
.GetCount();
471 for ( size_t n
= 0; n
< count
; n
++ )
473 if ( m_running
[n
]->HasInput() )
480 // ----------------------------------------------------------------------------
482 // ----------------------------------------------------------------------------
484 void MyProcess::OnTerminate(int pid
, int status
)
486 wxLogStatus(m_parent
, _T("Process %u ('%s') terminated with exit code %d."),
487 pid
, m_cmd
.c_str(), status
);
489 // we're not needed any more
493 // ----------------------------------------------------------------------------
495 // ----------------------------------------------------------------------------
497 bool MyPipedProcess::HasInput()
499 wxInputStream
& is
= *GetInputStream();
502 wxTextInputStream
tis(is
);
504 // this assumes that the output is always line buffered
506 msg
<< m_cmd
<< _T(": ") << tis
.ReadLine();
508 m_parent
->GetLogListBox()->Append(msg
);
518 void MyPipedProcess::OnTerminate(int pid
, int status
)
520 // show the rest of the output
524 m_parent
->OnProcessTerminated(this);
526 MyProcess::OnTerminate(pid
, status
);