Page 1 of 1

NewTab from event thread

PostPosted: Mon Jun 10, 2013 10:38 am
by pssgcsim
Hi I have problem with adding TabPage to TabControl in Windows Forms from event thread. In case like this one:

Calling event
Code: Select all
            browser.BeforePopup += (s, e) =>
            {
                NewTab(e.url);
            };

NewTab modifiers
Code: Select all
public void NewTab(string url)

Error showed by MS Visual Studio on line
Code: Select all
            _tabs.TabPages.Add(tabPage);

Re: NewTab from event thread

PostPosted: Tue Jun 11, 2013 4:55 am
by fddima
Run NewTab in correct thread (winforms UI thread).

Re: NewTab from event thread

PostPosted: Tue Jun 11, 2013 6:36 am
by pssgcsim
And how can I do it from event please ?

Re: NewTab from event thread

PostPosted: Tue Jun 11, 2013 7:10 am
by pssgcsim
Thx I got it :D
Code: Select all
_pUIThread.Post((_state) => { NewTab(url); }, null);

Re: NewTab from event thread

PostPosted: Tue Jun 11, 2013 7:41 am
by fddima
pssgcsim wrote:Thx I got it :D
Code: Select all
_pUIThread.Post((_state) => { NewTab(url); }, null);

Yeah, correctly.

Re: NewTab from event thread

PostPosted: Tue May 06, 2014 1:59 pm
by mistymorning
The way that I do this is to add a static referance to the control from Form_Load

WebBrowser.TabControl = this.TabPages1;

then from the code that needs to add a new tab page i switch to the UI thread by using

public static void NewTab(string url)
{//Called on the browser thread
WebBrowser.Url = url;
WebBrowser.TabControl .BeginInvoke(new Action(NewTab));
}

public static void NewTab()
{//Called on the UI thread
AddNewTab(WebBrowser.Url,true);
}


In addNewTab I create a new tabpage and then a browser control and add the borwser to the .tag of the new tabpage and then add the tabpage to the collection of pages in the tabcontrol thats on the form.

later I use a form timer to get the tabcontrol.selectedtab and cast the tag back to a browser control and then I can set other buttons on the main form using
WebBrowser B=(WebBrowser)TabPages1.selected.tag
CmdForward.Enabled=B.CanGoForwards;

You don't need to worry about cross thread errors on int or bool values but you might need locking on strings that are set from browser threads !!!