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

时间:2013-08-19 23:13:25

标签: c# visual-studio visual-studio-2012

我正在使用Visual Studio创建程序。到目前为止,它有一个带按钮的窗口。

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

    }
}

在Form1.cs中:

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

...但单击按钮后它不会更改窗口文本。我在更改文本后也尝试了formMain.ActiveForm.Refresh(),但这不起作用。我搜索高低解决方案,但我是C#的新手。你们中有人对我有什么想法吗?

2 个答案:

答案 0 :(得分:2)

你有没有尝试过类似的东西?

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

答案 1 :(得分:0)

首先,永远不要编辑designer.cs代码。这是自动生成的,如果您编辑文件,则可能会中断。

其次,使用您向我们展示的代码formMain尚未初始化为任何内容,因此您尝试设置属性(例如其Text属性)时会出错。所以你有两个选择:

  1. formMain设置为您的表单(由于下一个选项而不推荐)
  2. 使用this对象。 this指的是您正在使用的当前对象(在这种情况下,您指的是您的表单)。
  3. 您可以设置表单的Text属性来更改表单的标题。例如:

    this.Text = "Hello World!";