my_dll.cpp 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. /////////////////////////////////////////////////////////////////////////////
  2. // Name: my_dll.cpp
  3. // Purpose: Sample showing how to use wx from a DLL
  4. // Author: Vaclav Slavik
  5. // Created: 2009-12-03
  6. // Copyright: (c) 2009 Vaclav Slavik
  7. // Licence: wxWindows licence
  8. /////////////////////////////////////////////////////////////////////////////
  9. // ============================================================================
  10. // declarations
  11. // ============================================================================
  12. // ----------------------------------------------------------------------------
  13. // headers
  14. // ----------------------------------------------------------------------------
  15. #include "wx/wxprec.h"
  16. #ifdef __BORLANDC__
  17. #pragma hdrstop
  18. #endif
  19. #ifndef __WINDOWS__
  20. #error "This sample is Windows-only"
  21. #endif
  22. #include "wx/app.h"
  23. #include "wx/dynlib.h"
  24. #include "wx/frame.h"
  25. #include "wx/panel.h"
  26. #include "wx/sizer.h"
  27. #include "wx/stattext.h"
  28. #include "wx/button.h"
  29. #include "wx/thread.h"
  30. #include "wx/msgdlg.h"
  31. #include "wx/msw/wrapwin.h"
  32. #include <process.h> // for _beginthreadex()
  33. #include "my_dll.h"
  34. // ----------------------------------------------------------------------------
  35. // GUI classes
  36. // ----------------------------------------------------------------------------
  37. class MyDllFrame : public wxFrame
  38. {
  39. public:
  40. MyDllFrame(wxWindow *parent, const wxString& label);
  41. void OnAbout(wxCommandEvent& event);
  42. wxDECLARE_EVENT_TABLE();
  43. };
  44. static const int CMD_SHOW_WINDOW = wxNewId();
  45. static const int CMD_TERMINATE = wxNewId();
  46. class MyDllApp : public wxApp
  47. {
  48. public:
  49. MyDllApp();
  50. private:
  51. void OnShowWindow(wxThreadEvent& event);
  52. void OnTerminate(wxThreadEvent& event);
  53. };
  54. // ============================================================================
  55. // implementation
  56. // ============================================================================
  57. // ----------------------------------------------------------------------------
  58. // MyDllFrame
  59. // ----------------------------------------------------------------------------
  60. wxBEGIN_EVENT_TABLE(MyDllFrame, wxFrame)
  61. EVT_BUTTON(wxID_ABOUT, MyDllFrame::OnAbout)
  62. wxEND_EVENT_TABLE()
  63. MyDllFrame::MyDllFrame(wxWindow *parent, const wxString& label)
  64. : wxFrame(parent, wxID_ANY, label)
  65. {
  66. wxPanel *p = new wxPanel(this, wxID_ANY);
  67. wxSizer *sizer = new wxBoxSizer(wxVERTICAL);
  68. sizer->Add
  69. (
  70. new wxStaticText
  71. (
  72. p, wxID_ANY,
  73. wxString::Format
  74. (
  75. "Running using %s\n"
  76. "wxApp instance is %p, thread ID %ld",
  77. wxVERSION_STRING,
  78. wxApp::GetInstance(),
  79. wxThread::GetCurrentId()
  80. )
  81. ),
  82. wxSizerFlags(1).Expand().Border(wxALL, 10)
  83. );
  84. sizer->Add
  85. (
  86. new wxButton(p, wxID_ABOUT, "Show info"),
  87. wxSizerFlags(0).Right().Border(wxALL, 10)
  88. );
  89. p->SetSizerAndFit(sizer);
  90. wxSizer *fsizer = new wxBoxSizer(wxVERTICAL);
  91. fsizer->Add(p, wxSizerFlags(1).Expand());
  92. SetSizerAndFit(fsizer);
  93. }
  94. void MyDllFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
  95. {
  96. wxMessageBox("This window is running in its own thread,\n"
  97. "using private wxWidgets instance compiled into the DLL.",
  98. "About",
  99. wxOK | wxICON_INFORMATION);
  100. }
  101. // ----------------------------------------------------------------------------
  102. // MyDllApp
  103. // ----------------------------------------------------------------------------
  104. MyDllApp::MyDllApp()
  105. {
  106. // Keep the wx "main" thread running even without windows. This greatly
  107. // simplifies threads handling, because we don't have to correctly
  108. // implement wx-thread restarting.
  109. //
  110. // Note that this only works if you don't explicitly call ExitMainLoop(),
  111. // except in reaction to wx_dll_cleanup()'s message. wx_dll_cleanup()
  112. // relies on the availability of wxApp instance and if the event loop
  113. // terminated, wxEntry() would return and wxApp instance would be
  114. // destroyed.
  115. //
  116. // Also note that this is efficient, because if there are no windows, the
  117. // thread will sleep waiting for a new event. We could safe some memory
  118. // by shutting the thread down when it's no longer needed, though.
  119. SetExitOnFrameDelete(false);
  120. Connect(CMD_SHOW_WINDOW,
  121. wxEVT_THREAD,
  122. wxThreadEventHandler(MyDllApp::OnShowWindow));
  123. Connect(CMD_TERMINATE,
  124. wxEVT_THREAD,
  125. wxThreadEventHandler(MyDllApp::OnTerminate));
  126. }
  127. void MyDllApp::OnShowWindow(wxThreadEvent& event)
  128. {
  129. wxFrame *f = new MyDllFrame(NULL, event.GetString());
  130. f->Show(true);
  131. }
  132. void MyDllApp::OnTerminate(wxThreadEvent& WXUNUSED(event))
  133. {
  134. ExitMainLoop();
  135. }
  136. // ----------------------------------------------------------------------------
  137. // application startup
  138. // ----------------------------------------------------------------------------
  139. // we can't have WinMain() in a DLL and want to start the app ourselves
  140. IMPLEMENT_APP_NO_MAIN(MyDllApp)
  141. namespace
  142. {
  143. // Critical section that guards everything related to wxWidgets "main" thread
  144. // startup or shutdown.
  145. wxCriticalSection gs_wxStartupCS;
  146. // Handle of wx "main" thread if running, NULL otherwise
  147. HANDLE gs_wxMainThread = NULL;
  148. // wx application startup code -- runs from its own thread
  149. unsigned wxSTDCALL MyAppLauncher(void* event)
  150. {
  151. // Note: The thread that called run_wx_gui_from_dll() holds gs_wxStartupCS
  152. // at this point and won't release it until we signal it.
  153. // We need to pass correct HINSTANCE to wxEntry() and the right value is
  154. // HINSTANCE of this DLL, not of the main .exe, use this MSW-specific wx
  155. // function to get it. Notice that under Windows XP and later the name is
  156. // not needed/used as we retrieve the DLL handle from an address inside it
  157. // but you do need to use the correct name for this code to work with older
  158. // systems as well.
  159. const HINSTANCE
  160. hInstance = wxDynamicLibrary::MSWGetModuleHandle("my_dll",
  161. &gs_wxMainThread);
  162. if ( !hInstance )
  163. return 0; // failed to get DLL's handle
  164. // IMPLEMENT_WXWIN_MAIN does this as the first thing
  165. wxDISABLE_DEBUG_SUPPORT();
  166. // We do this before wxEntry() explicitly, even though wxEntry() would
  167. // do it too, so that we know when wx is initialized and can signal
  168. // run_wx_gui_from_dll() about it *before* starting the event loop.
  169. wxInitializer wxinit;
  170. if ( !wxinit.IsOk() )
  171. return 0; // failed to init wx
  172. // Signal run_wx_gui_from_dll() that it can continue
  173. HANDLE hEvent = *(static_cast<HANDLE*>(event));
  174. if ( !SetEvent(hEvent) )
  175. return 0; // failed setting up the mutex
  176. // Run the app:
  177. wxEntry(hInstance);
  178. return 1;
  179. }
  180. } // anonymous namespace
  181. // ----------------------------------------------------------------------------
  182. // public DLL interface
  183. // ----------------------------------------------------------------------------
  184. extern "C"
  185. {
  186. void run_wx_gui_from_dll(const char *title)
  187. {
  188. // In order to prevent conflicts with hosting app's event loop, we
  189. // launch wx app from the DLL in its own thread.
  190. //
  191. // We can't even use wxInitializer: it initializes wxModules and one of
  192. // the modules it handles is wxThread's private module that remembers
  193. // ID of the main thread. But we need to fool wxWidgets into thinking that
  194. // the thread we are about to create now is the main thread, not the one
  195. // from which this function is called.
  196. //
  197. // Note that we cannot use wxThread here, because the wx library wasn't
  198. // initialized yet. wxCriticalSection is safe to use, though.
  199. wxCriticalSectionLocker lock(gs_wxStartupCS);
  200. if ( !gs_wxMainThread )
  201. {
  202. HANDLE hEvent = CreateEvent
  203. (
  204. NULL, // default security attributes
  205. FALSE, // auto-reset
  206. FALSE, // initially non-signaled
  207. NULL // anonymous
  208. );
  209. if ( !hEvent )
  210. return; // error
  211. // NB: If your compiler doesn't have _beginthreadex(), use CreateThread()
  212. gs_wxMainThread = (HANDLE)_beginthreadex
  213. (
  214. NULL, // default security
  215. 0, // default stack size
  216. &MyAppLauncher,
  217. &hEvent, // arguments
  218. 0, // create running
  219. NULL
  220. );
  221. if ( !gs_wxMainThread )
  222. {
  223. CloseHandle(hEvent);
  224. return; // error
  225. }
  226. // Wait until MyAppLauncher signals us that wx was initialized. This
  227. // is because we use wxMessageQueue<> and wxString later and so must
  228. // be sure that they are in working state.
  229. WaitForSingleObject(hEvent, INFINITE);
  230. CloseHandle(hEvent);
  231. }
  232. // Send a message to wx thread to show a new frame:
  233. wxThreadEvent *event =
  234. new wxThreadEvent(wxEVT_THREAD, CMD_SHOW_WINDOW);
  235. event->SetString(title);
  236. wxQueueEvent(wxApp::GetInstance(), event);
  237. }
  238. void wx_dll_cleanup()
  239. {
  240. wxCriticalSectionLocker lock(gs_wxStartupCS);
  241. if ( !gs_wxMainThread )
  242. return;
  243. // If wx main thread is running, we need to stop it. To accomplish this,
  244. // send a message telling it to terminate the app.
  245. wxThreadEvent *event =
  246. new wxThreadEvent(wxEVT_THREAD, CMD_TERMINATE);
  247. wxQueueEvent(wxApp::GetInstance(), event);
  248. // We must then wait for the thread to actually terminate.
  249. WaitForSingleObject(gs_wxMainThread, INFINITE);
  250. CloseHandle(gs_wxMainThread);
  251. gs_wxMainThread = NULL;
  252. }
  253. } // extern "C"