Process.mainwindowtitle 使用 Visual Studio 返回空字符串

编程


我有 Windows 11 。 我在 VS2019(C#) 中有一个控制台应用程序。
我正在尝试通过 system.Diagnostics.Process 启动计算器 exe。

代码片段:

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());

运行上面的代码后,计算器 exe 正在启动,但 myProcess.MainWindowTitle 返回一个空字符串。 我无法理解这个事实。 请帮忙。

我尝试过的:

我尝试运行上面的代码以获取 MainWidowsTitle 的值。 但即使计算器正在启动,“MainWindowTitle”的值也是空字符串。

解决方案1

C:\Windows\System32\calc.exe 只是一个启动另一个进程的存根。 如果您查看进程对象,它就会退出。

在我的 Windows 10 系统上 calc.exe 实际上启动了计算器“应用程序”,它是
C:\Program Files\WindowsApps\Microsoft.WindowsCalculator_10.2103.8.0_x64__8wekyb3d8bbwe\Calculator.exe

无法直接启动。

解决方案2

您的问题可能与运行代码和调用窗口标题之间的时间有关。 在进程进入空闲状态后尝试检索标题之前,您需要检查主窗口句柄。

我为您添加了一个名为“GetMainWindowTitle”的方法来检查主窗口句柄 –

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をコピーしました