Process.mainwindowtitle devuelve una cadena vacía usando Visual Studio

programación


Tengo windows 11. Tengo una aplicación de consola en VS2019(C#).
Estoy intentando iniciar la calculadora exe a través del sistema.Diagnostics.Process.

fragmento de código:

C#
ProcessStartInfo startInfo = new ProcessStartInfo(@"C:\Windows\System32\calc.exe");

            //startInfo.RedirectStandardOutput = true;
            startInfo.UseShellExecute = false;
            startInfo.WindowStyle = ProcessWindowStyle.Normal;

            var myProcess = Process.Start(startInfo);

            myProcess.WaitForInputIdle();

            Console.Write("Main window Title : " + myProcess.MainWindowTitle.ToString());

Después de ejecutar el código anterior, se inicia el exe de la calculadora, pero myProcess.MainWindowTitle devuelve una cadena vacía. No soy capaz de entender este hecho. Por favor ayuda.

Lo que he probado:

Intenté ejecutar el código anterior para obtener el valor de MainWidowsTitle. Pero aunque se está iniciando la calculadora, el valor de ‘MainWindowTitle’ es una cadena vacía.

Solución 1

C:\Windows\System32\calc.exe es solo un código auxiliar que inicia otro proceso. Si observa su objeto de proceso, habrá salido.

En mi sistema Windows 10, calc.exe realmente inicia la “aplicación” de la calculadora, que es
C:\Archivos de programa\WindowsApps\Microsoft.WindowsCalculator_10.2103.8.0_x64__8wekyb3d8bbwe\Calculator.exe

No se puede iniciar directamente.

Solución 2

Su problema podría estar relacionado con el tiempo entre la ejecución de su código y la llamada al Título de la ventana. Debe verificar el identificador de la ventana principal antes de intentar recuperar el título después de que el proceso haya entrado en estado inactivo.

He agregado un método llamado ‘GetMainWindowTitle’ para verificar el identificador de la ventana principal.

C#
using System;
using System.Diagnostics;

class RunandReadMyProgram
{
    static void Main()
    {
        //Create a new process start info...
        ProcessStartInfo startInfo = new ProcessStartInfo(@"C:\Windows\System32\calc.exe");

        //Configure your startInfo properties...
        startInfo.UseShellExecute = false;
        startInfo.WindowStyle = ProcessWindowStyle.Normal;

        //Start your processing...
        var myProcess = Process.Start(startInfo);

        //Wait for your process to enter the idle state before reading the title...
        myProcess.WaitForInputIdle();

        //Retrieve the main window title once your process is idle...
        string mainWindowTitle = GetMainWindowTitle(myProcess);

        //Display the main window title where you need it...
        Console.WriteLine("Calculator Window Title: " + mainWindowTitle);
    }

    //The method to get the main window title of your process...
    static string GetMainWindowTitle(Process process)
    {
        string title = string.Empty;

        //Check if your process has a main window handle...
        if (process.MainWindowHandle != IntPtr.Zero)
        {
            //Read the title of the main window...
            title = process.MainWindowTitle;
        }

        return title;
    }
}

コメント

タイトルとURLをコピーしました