Console application crashes after opening a web browser form because of a threadestate exception

128 Views Asked by At

I am developing a console application that visualizes steam items that have been filtered by name by making an html file (I am making a steam trade bot).

In one part of the program I call a Windows form that contains a web browser (my app is console application type) when the form load the web browser is set to navigate to google just for debuging, but i get this error.

My console application:

[STAThread]
public override void OnMessage(string message, EChatEntryType type)
{
    switch(message)
    {
        ....
        case "!show":
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
            break;
        }
    }
}

and my form:

private void Navigate(String address)
{
    if (String.IsNullOrEmpty(address)) return;
    if (address.Equals("about:blank")) return;
    if (!address.StartsWith("http://") &&
        !address.StartsWith("https://"))
    {
        address = "http://" + address;
    }
    try
    {
        webBrowser1.Navigate(new Uri(address));
    }
    catch (System.UriFormatException)
    {
        return;
    }
}  
private void Form1_Load(object sender, EventArgs e)
{
    Navigate("google.com");
}

I can't find a solution. I tried to make a new Thread but it didnt work.

1

There are 1 best solutions below

0
On

Well, the error message says it: ... because the current thread is not in a single-threaded apartment.

You already have a STAThread attribute, but you need to apply it to the entry method of the thread, i.e. the method that is executed when the thread starts, and what in your case probably is the Main method:

class Program
{
  [STAThread]
  static void Main(string[] args)
  {
  // ...