我想在textBox中显示当前表单Title 但是下面的代码不会这样做,它只有在我将它设置在Button1_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)
{
}
}
}
答案 0 :(得分:1)
这个简单的代码演示了当调用Form.Load事件的事件处理程序时,没有从currentp
读取的MainWindowTitle,而如果你在Form.Shown事件处理程序中执行相同的代码,则有一个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";
}