returning an object from a class in C# (wpf) -


i trying call class called threadcreator() , 1 of methods called createwindow() , have return new window created can use object somewhere else invoke method on it.

here's breakdown. thread creator class pops new wpf window on new thread:

using system; using system.threading; using system.diagnostics; using system.io; using system.componentmodel; using system.windows;  namespace windamow { public static class threadcreator {      private static newwindow w;      public static newwindow createwindow()     {         string appname = "";         try         {             appname = path.getfilename(system.reflection.assembly.getentryassembly().location);             const string ie_emulation = @"software\microsoft\internet explorer\main\featurecontrol\feature_browser_emulation";             using (var fbekey = microsoft.win32.registry.currentuser.opensubkey(ie_emulation, true))             {                 fbekey.setvalue(appname, 9000, microsoft.win32.registryvaluekind.dword);             }         }         catch (exception ex)         {             messagebox.show(appname + "\n" + ex.tostring(), "unexpected error setting browser mode!");         }          thread t = new thread(threadproc);         t.setapartmentstate(apartmentstate.sta);         t.start();          return w;     }      private static void threadproc(object obj)     {         w = new newwindow();         w.showdialog();     } } } 

new window.xaml.cs looks this:

using system; using system.windows; using system.windows.controls; using system.runtime.interopservices; using system.diagnostics;  namespace windamow { /// <summary> /// interaction logic newwindow.xaml /// </summary> public partial class newwindow : window {     string _message;     public string message     {         { return _message; }         set         {             _message = value;             this.dispatcher.invoke(() => { this.webbrowser.navigatetostring(_message); });         }     }      [dllimport("user32.dll")]     public static extern intptr getforegroundwindow();      intptr _handle;     public intptr handle { { return _handle; } }      int _pid;     public int pid { { return _pid; } }      public newwindow()     {         initializecomponent();     }      private void window_closed(object sender, eventargs e)     {         windownotifier.oniamclosed(handle);     }      private void window_closing(object sender, system.componentmodel.canceleventargs e)     {         windownotifier.oniamclosing(handle);     }      private void window_loaded(object sender, routedeventargs e)     {         _pid = process.getcurrentprocess().id;         _handle = getforegroundwindow();          windownotifier.oniamcreated(handle);     } } } 

what trying window invoke navigatetostring() method every time method called checkifwindowopen() run. check if window open , either open , execute navigatetostring() or execute navigatetostring() possibly new inputs (refresh).

here's how calling it:

namespace windamow { public class win32f {     [dllimport("user32.dll")]     public static extern bool iswindowvisible(intptr hwnd);      [dllimport("user32.dll")]     public static extern intptr getforegroundwindow(); }  public class dynamodataviznodes {     [dllimport("user32.dll", setlasterror = true)]     public static extern int getlasterror();      // test html string     public static string htmlstring = "<html></html>";      intptr handleofwindowonnewthread;      void windownotifier_iamcreatedevent(intptr handle)     {         handleofwindowonnewthread = handle;          debug.writeline(string.format("i created : {0}", handle));     }      void windownotifier_iamclosedevent(intptr handle)     {         if (handleofwindowonnewthread == handle)             handleofwindowonnewthread = intptr.zero;          debug.writeline(string.format("i closed : {0}", handle));     }      void windownotifier_iamclosingevent(intptr handle)     {         debug.writeline(string.format("i closing : {0}", handle));     }      public static newwindow window;      public void checkifwindowopen(string sourcestring)     {         windownotifier.iamclosingevent += windownotifier_iamclosingevent;         windownotifier.iamclosedevent += windownotifier_iamclosedevent;         windownotifier.iamcreatedevent += windownotifier_iamcreatedevent;          if (handleofwindowonnewthread == intptr.zero)         {             // create new window , set browser             window = threadcreator.createwindow();             window.dispatcher.invoke(() => { window.webbrowser.navigatetostring(sourcestring); });          }         else         {              // set browser             window.dispatcher.invoke(() => { window.webbrowser.navigatetostring(sourcestring); });         }       } } } 

the error happens in checkifwindowopen() method when trying return newwindow object invoke navigatetostring() method on it. returns null. there way make threadcreator.createwindow() return created window?

thanks!

solution1 : without storing reference newwindow in mainwindow. instead raising refreshbrowser event mainwindow. dropbox link

solution2 : storing reference newwindow in mainwindow : new solution changed requirements : dropbox link

  1. thread creation routine doesn't wait threadprocedure run, return value null always. can use value in other event handler. because once routine finishes, variable window contain valid value.

  2. however not proper way trying do.

  3. there cleaner way in today's event driven programming world. remember, controls/windows fire events , access sender , additional info using corresponding eventargs. eg;

    private void window_loaded(object sender, routedeventargs e)

  4. following same pattern above, modify our delegates below :

    public static class windownotifier2 {     public static event createddelegatecallback iamcreatedevent;     public delegate void createddelegatecallback(object sender, windownotifiereventargs args);      public static event closingdelegatecallback iamclosingevent;     public delegate void closingdelegatecallback(object sender, windownotifiereventargs args);      public static event closeddelegatecallback iamclosedevent;     public delegate void closeddelegatecallback(object sender, windownotifiereventargs args);       public static void oniamcreated(object sender, windownotifiereventargs args)     {         if (iamcreatedevent != null)             iamcreatedevent(sender, args);     }      public static void oniamclosing(object sender, windownotifiereventargs args)     {         if (iamclosingevent != null)             iamclosingevent(sender, args);     }      public static void oniamclosed(object sender, windownotifiereventargs args)     {         if (iamclosedevent != null)             iamclosedevent(sender, args);     }  }  public class windownotifiereventargs : eventargs {     public intptr windowhandle { get; set; } } 

...

newwindow.xaml.cs

private void window_loaded(object sender, routedeventargs e) {    _pid = process.getcurrentprocess().id;                        _handle = getforegroundwindow();     windownotifier2.oniamcreated(this, new windownotifiereventargs() { windowhandle = _handle }); }       

mainwindow.xaml.cs

private void btnchecknewwindow_click(object sender, routedeventargs e)         {             if (handleofwindowonnewthread == intptr.zero)             {                 windownotifier2.iamcreatedevent += (object source, windownotifiereventargs args) =>                 {                     _newwindow = (newwindow)source;                      handleofwindowonnewthread = args.windowhandle;                     debug.writeline(string.format("i created : {0}", args.windowhandle));                      _newwindow.tbmsgfrommainwindow.dispatcher.invokeasync(() => {                          _newwindow.tbmsgfrommainwindow.text = "i created ! creator.";                      });                 };                  threadcreator.createwindow();             }             else             {                 _newwindow.tbmsgfrommainwindow.dispatcher.invokeasync(() => {                      _newwindow.tbmsgfrommainwindow.text = "i can see running !";                  });             }         }  

Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -