user287848
user287848

Reputation: 141

InvalidOperationException when making Main Form Visible

I am adding a sys tray function to my program, as it will primarily run in the background. When it gets to badFiles32, it says "Cross-thread operation not valid: Control 'mainForm' accessed from a thread other than the thread it was created on". I don't recall having this issue in the past, I know I've made other applications run in the sys tray. This application is not complicated at all, and I'm not taking advantage of multi-threading.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Me.WindowState = FormWindowState.Minimized
    Me.Visible = False
End Sub


Sub badFiles32(ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) Handles pFiles32.Created
    Me.WindowState = FormWindowState.Normal
    Me.Visible = True

'More code below
End Sub

Private Sub blockBTN_Click(sender As System.Object, e As System.EventArgs) Handles blockBTN.Click
    Me.WindowState = FormWindowState.Minimized
    Me.Visible = False
'More Code Below
End Sub

Upvotes: 1

Views: 468

Answers (3)

Enes Genc
Enes Genc

Reputation: 196

This disables the exception

Me.CheckForIllegalCrossThreadCalls = False

But delegate is real solution simply like this:

thread = New System.Threading.Thread(AddressOf DoStuff)
thread.Start()

--

Private Delegate Sub DoStuffDelegate()
Private Sub DoStuff()
    If Me.InvokeRequired Then
        Me.Invoke(New DoStuffDelegate(AddressOf DoStuff))
    Else
        Me.Text = "Stuff"
    End If
End Sub

Upvotes: 0

Mark Hall
Mark Hall

Reputation: 54532

Your FileSystemWatcher has a SynchronizingObject Property. If you create your FileSystemWatcher in the Code behind like you are doing in your previous question, that property will be null. You will need to set it to your Form in your initialization and it should work.

 pFiles32.SynchronizingObject = Me

From above link:

When SynchronizingObject is null, methods handling the Changed, Created, Deleted, and Renamed events are called on a thread from the system thread pool. For more information on system thread pools, see ThreadPool.

When the Changed, Created, Deleted, and Renamed events are handled by a visual Windows Forms component, such as a Button, accessing the component through the system thread pool might not work, or may result in an exception. Avoid this by setting SynchronizingObject to a Windows Forms component, which causes the methods that handle the Changed, Created, Deleted, and Renamed events to be called on the same thread on which the component was created.

Upvotes: 2

Visual Vincent
Visual Vincent

Reputation: 18310

Try using Me.Hide() and Me.Show() instead. Me.Hide() will make the form invisible but it can still be accessed and used.

Upvotes: 1

Related Questions