C# 加载时加载文本框表单标题

C# 加载时加载文本框表单标题,c#,C#,我想在文本框中显示当前表单标题 但是下面的代码不起作用,只有当我将其设置为Button1\u click时,它才起作用。 单击按钮后,它将更改为表单标题 但我需要它在加载时立即在文本框中设置表单标题 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.

我想在文本框中显示当前表单标题 但是下面的代码不起作用,只有当我将其设置为Button1\u click时,它才起作用。 单击按钮后,它将更改为表单标题 但我需要它在加载时立即在文本框中设置表单标题

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;

namespace ShowTitle
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Process currentp = Process.GetCurrentProcess();
        textBox1.Text = currentp.MainWindowTitle;


    }

    private void button1_Click(object sender, EventArgs e)
    {

    }
}
}

这段简单的代码演示了当调用Form.Load事件的事件处理程序时,从
currentp
读取的MainWindowTitle不存在,而如果在Form.Showed事件处理程序中执行相同的代码,则currentp变量中有一个MainWindowTitle

Form f;
TextBox t;
void Main()
{
    f = new Form();
    f.Text = "This is a test";
    t = new TextBox();
    f.Controls.Add(t);
    f.Load += onLoad;
    f.Shown += onShow;
    f.Show();
}
void onLoad(object sender, EventArgs e)
{
    Process currentp = Process.GetCurrentProcess();
    if(!string.IsNullOrWhiteSpace(currentp.MainWindowTitle))
        t.Text = currentp.MainWindowTitle;
    else
        t.Text = "NO TITLE";
}

void onShow(object sender, EventArgs e)
{
    // Uncomment these line to see the differences
    // if(!string.IsNullOrWhiteSpace(currentp.MainWindowTitle))
    //     t.Text = currentp.MainWindowTitle;
    // else
    //     t.Text = "NO TITLE";
}

请尝试使用“显示的事件”形式,而不是在显示的
InitializeComponent
Did
private void Form1\u(对象发送者,事件参数){Process currentp=Process.getcurrentproces();textBox1.Text=currentp.MainWindowTitle;}之后添加此代码
在初始化Component后添加,没有区别,也没有区别。这很奇怪,因为当显示的Form1\u被调用时,主窗口可用,您可以读取它。您确定已执行事件代码吗?因为所显示的事件有效,所以已向上投票。不知道为什么不适合OP。我做的另一个测试是使加载事件异步,然后等待任务。延迟(10),然后再创建实际工作的进程。是的,这在这个简单的场景中也应该工作,但我有点不确定使Form_加载异步是否是一个好主意。太多的底层流程在事件序列中工作,导致屏幕上显示一个表单,在那个时间点很容易搞乱它们。哦。是的,这只是一个测试,OP必须使用
显示的
事件。我只是想确保表单的某些部分当时没有被创建。