简体   繁体   English

我似乎无法在C#中更改窗体格式文本

[英]I can't seem to change the window form text in C#

I'm using Visual Studio to create a program. 我正在使用Visual Studio来创建程序。 So far, it has one window with a button. 到目前为止,它有一个带按钮的窗口。

in Form1.Designer.cs, it initializes the window: 在Form1.Designer.cs中,它初始化窗口:

namespace Test
{
    private void InitializeComponent()
    {
        // I took out everything else, it isn't needed.

        // 
        // formMain
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.BackColor = System.Drawing.SystemColors.ControlLightLight;
        this.ClientSize = new System.Drawing.Size(624, 442);
        this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
        this.Name = "formMain";
        this.Text = "Program Name";
        this.Load += new System.EventHandler(this.formMain_Load);
        this.menuBar.ResumeLayout(false);
        this.menuBar.PerformLayout();
        this.ResumeLayout(false);
        this.PerformLayout();

    }
}

In Form1.cs: 在Form1.cs中:

    private void button1_Click(object sender, EventArgs e)
    {
        formMain.ActiveForm.Text = formMain.ActiveForm.Text + " - Project Name";
    }

...but it doesn't change the window text after I click the button. ...但是单击按钮后它不会更改窗口文本。 I've also tried formMain.ActiveForm.Refresh() after changing the text, but that didn't work. 我在更改文本后也尝试过formMain.ActiveForm.Refresh() ,但是没有用。 I've search high and low for a solution, but I'm new to C#. 我搜索高低解决方案,但我是C#的新手。 Do any of you have any ideas for me? 你们有什么想法吗?

Did you try something like that? 你尝试过类似的东西吗?

private void button1_Click(object sender, EventArgs e)
{
    this.Text = "Works!";
}

First, never edit designer.cs code. 首先,永远不要编辑designer.cs代码。 This is auto-generated and you can break things if you edit the file. 这是自动生成的,如果您编辑文件,则可以解决问题。

Second, with the code you showed us formMain has not been initialized to anything so it will error out of you try to set properties (such as its Text property). 其次,使用您向我们展示的代码, formMain尚未初始化为任何内容,因此您尝试设置属性(例如其Text属性)时会出错。 So you have two options: 所以你有两个选择:

  1. Set formMain to your form (not recommended due to the next option) formMain设置为您的表单(由于下一个选项,不推荐)
  2. Use the this object. 使用this对象。 this refers to the current object you are working with (in this case you are referring to your form). this指的是您正在使用的当前对象(在这种情况下,您指的是您的表单)。

You can set the form's Text property to change the form's title. 您可以设置表单的Text属性来更改表单的标题。 For example: 例如:

this.Text = "Hello World!";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM