I'm not able to seek for all WPF windows

Viewed 71

I'm using WMI to detect when a process is closed or open, when is open I rise a new thread to open a new window. When the process is closed this window must be closed but I can't closed it because I ain't able to get the windows instance I have.

private ManagementEventWatcher EventWatcher(string process)
{
    string query = String.Format(@"
        SELECT * 
        FROM __InstanceOperationEvent 
        WITHIN {0} 
        WHERE TargetInstance ISA 'Win32_Process' 
        AND TargetInstance.Name = '{1}'", "1", process
    );

    string scope = @"\\.\root\CIMV2";
    return new ManagementEventWatcher(scope, query);
}


private void GameWatcher() 
{
    ManagementEventWatcher GAMEWatcher = EventWatcher("notepad.exe");

    GAMEWatcher.EventArrived += new EventArrivedEventHandler(OnEventArrived_Game);
    GAMEWatcher.Start();
}

private void OnEventArrived_Game(object sender, EventArrivedEventArgs e)
{
    // If process is open. 
    if (e.NewEvent.ClassPath.ClassName.Contains("InstanceCreationEvent") && !(summonerName is null)) {
        Thread thread = new Thread(RiseWindow);
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
    }


    // If process is closed
    if (e.NewEvent.ClassPath.ClassName.Contains("InstanceDeletionEvent"))
    {
        // Detect windows (This doesn't work and throw the follow exceptions)
        foreach (Window window in Application.Current.Windows)
        {
            Console.WriteLine(window.Title);
        }
    }
}

private static void RiseWindow()
{
    new InGame("Pabloch0", KEY).ShowDialog();
}

The code throws the next exceptions, I assume it's because I'm trying detect windows from a thread?

'System.InvalidOperationException' in WindowsBase.dll
'System.Reflection.TargetInvocationException' in mscorlib.dll

System.InvalidOperationException: 'The calling thread cannot access this object because a different thread owns it.'

is there any other way to get the windows instance in WPF or close it?

EDIT:

Using Dispatcher I'm able to get only the main windows but not the other one that's opened previously in the thread.

Action readWindows = () => {

    foreach (Window window in Application.Current.Windows)
    {
        Console.WriteLine(window.Title);
    }

};

Dispatcher.BeginInvoke(readWindows);

0 Answers
Related