Accessing a control without using Invoke in C #
I have a form with a WebBrowser control and an additional separate thread that controls the browser and waits for it to load. Here's some sample code:
private void Form1_Load(object sender, EventArgs e){
JobClass.mainAsync();
}
-
public static class JobClass
{
public static void mainAsync()
{
Thread t = new Thread(main);
t.Start();
}
private static void main()
{
Form1 frm = (Form1)Application.OpenForms["Form1"];
WebBrowser wb = frm.webBrowser1;
gotoGoogle(frm, wb);
}
private static void gotoGoogle(Form1 frm, WebBrowser wb)
{
frm.Invoke((MethodInvoker)delegate
{
wb.Navigate("google.com");
string loc = wb.Document.Url.AbsolutePath;
// ... some extra code ...
});
}
private static void gotoYoutube(Form1 frm, WebBrowser wb)
{
frm.Invoke((MethodInvoker)delegate
{
wb.Navigate("youtube.com");
wb.Document.Body.getElementById("...");
// ... some extra code ...
});
}
}
Everything works fine, but as you can see, I need to pass a variable Form1
for each method that uses the browser control, and I need to write frm.Invoke()
in all of them, which makes my code less portable and more painful as the code gets bigger.
I was wondering if there is something I could do inside the "main ()" method to make WebBrowser
it possibly a child of the same thread, so I don't have to constantly call it from the form? If not, how can I get rid of this ugly link?
source to share
you can do the following
- define an event in your JobClass, call it OnNavigationChanged
- handle the event in your Form1
- in the handled event method you can call wb.Navigate (url);
here's a code example
1- JobClass delegate
// define this delegate just above JobClass
public delegate void JobClassNavigationEvent(string url);
2- define event
public delegate void JobClassNavigationEvent(string url);
public static class JobClass
{
public static event JobClassNavigationEvent OnNavigationChanged;
private static BackgroundWorker worker;
public static void mainAsync()
{
worker = new BackgroundWorker();
worker.DoWork += (s, e) =>
{
main();
};
worker.RunWorkerAsync();
}
private static void main()
{
gotoGoogle();
}
private static void gotoGoogle()
{
if (OnNavigationChanged != null)
OnNavigationChanged.Invoke("google.com");
}
private static void gotoYoutube()
{
if (OnNavigationChanged != null)
OnNavigationChanged.Invoke("youtube.com");
}
}
3- in your form
private void Form1_Load(object sender, EventArgs e){
JobClass.OnNavigationChanged+=(url)=>{
webBrowser1.Navigate(url);
// other code come here
};
JobClass.mainAsync();
}
hope this helps you
source to share