0

I have a FileSystemWatcher watching for newly created files.

When it sees one, I would like it to open a child window.

Using this:

private void FileSystemWatcher_Created(object sender, FileSystemEventArgs e)
{
    TableWindow win = new TableWindow();
    win.Owner = this;
    win.Text = "xxx";
    win.ShowInTaskbar = false;
    win.Show();
}

The error I'm getting is:

Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on

After some googling. I ended up with this

TableWindow win = new TableWindow();
win.Owner = this;
win.Text = "xxx";
win.ShowInTaskbar = false;
win.Invoke((MethodInvoker)delegate
{
    win.Show();
});

which gives me a different error:

Invoke or BeginInvoke cannot be called on a control until the window handle has been created.

Here's the scenario. on a game, each time a new table is opened, a new file is created. When that file is created, I want to open a child window to display statistics on that table.

Is this even possible?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Bruce Thompson
  • 141
  • 1
  • 6

1 Answers1

1

What I've done in the past to work with InvokeRequired is to place it within an if statement that will call the method on the UI thread if it hasn't been called from the UI thread.

private void FileSystemWatcher_Created(object sender, FileSystemEventArgs e)
{
    ShowWindow();
}

private void ShowWindow()
{
    if (this.InvokeRequired)
    {
        var del = new MethodInvoker(ShowWindow);
        this.BeginInvoke(del);
        return;
    }
    TableWindow win = new TableWindow();
    win.Owner = this;
    win.Text = "xxx";
    win.ShowInTaskbar = false;
    win.Show();
}
Nate W
  • 275
  • 2
  • 13