Bird
Bird

Reputation: 11

Get MainWindow Instance WPF

I have some custom extensions, which when i double-click on it, it launch program and every time as i do it, it creates new mainwindow. So i want not create, but update the first mainwindow. I searced many articles, but don't find a way how to do it.

Now my code looks like this. I do it in App.xaml.cs with Startup event

private void Application_Startup(object sender, StartupEventArgs e)
        {
         

            Process currentProcess = Process.GetCurrentProcess();

            // Find the main window associated with the current process
            Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName);
            Process mainWindow = processes.FirstOrDefault(p => p.MainWindowHandle != IntPtr.Zero);

           
           

            if (e.Args.Length == 1)
            {
                //MessageBox.Show(e.Args[0]);
                FileInfo file = new FileInfo(e.Args[0]);
                filepathforwindow = file;

                if (mainWindow != null)
                {
                    try
                    {
                        IntPtr mainWindowHandle = mainWindow.MainWindowHandle;
                        MessageBox.Show(mainWindowHandle.ToString());
                        HwndSource hwndSource = HwndSource.FromHwnd(mainWindowHandle);
                        MainWindow mainW = hwndSource.RootVisual as MainWindow;


                        // Find the MainWindow by matching the handles

                        MessageBox.Show(mainW == null? "0": "1");

                        if (mainW != null)
                        {

                            // Now you have the MainWindow instance
                            // You can access its properties or methods
                            mainW.Load_From_File(file);
                        }
                    }
                    catch(Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }

                    

                }

             
            }
          
        }

I tried MainWindow mainWindow = Application.Current.Windows.OfType().FirstOrDefault();, also tried get it by process. Process is active, what's good, but mainWindow always null

Upvotes: 0

Views: 102

Answers (0)

Related Questions