在 C# 中居中显示窗体
本文关键字:显示 窗体 中居 | 更新日期: 2023-09-27 17:56:51
我是新来的,实际上我正在处理 C# 中的项目,在该项目中,我想在屏幕中央显示我的表单......为此,我编写了以下代码。
public class CenterForm : System.Windows.Forms.Form
{
private System.ComponentModel.Container components;
public CenterForm()
{
InitializeComponent();
CenterToScreen();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(107, 177);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "Ok";
this.button1.UseVisualStyleBackColor = true;
//
// CenterForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.Add(this.button1);
this.Name = "CenterForm";
this.Text = "DataGridExample";
this.Paint += new System.Windows.Forms.PaintEventHandler(this.CenterForm_Paint);
this.Resize += new System.EventHandler(this.CenterForm_Resize);
this.ResumeLayout(false);
}
[STAThread]
static void Main()
{
Application.Run(new CenterForm());
}
private void CenterForm_Resize(object sender, System.EventArgs e)
{
Invalidate();
Console.WriteLine("Resize");
}
private void CenterForm_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
Graphics g = e.Graphics;
g.DrawString("Text",
new Font("Times New Roman", 20),
new SolidBrush(Color.Black),
this.DisplayRectangle);
}
private Button button1;
}
但它给出了一些错误,即1)错误 1 '中心。Form1.Dispose(bool)':找不到合适的方法来覆盖 C:''Users''logicwaves''Documents''Visual Studio 2005''Projects''center''center''Form1.Designer.cs 14 33 center
2)错误 2 程序"C:''Users''logicwaves''Documents''Visual Studio 2005''Projects''center''center''obj''Debug''center.exe"定义了多个入口点:"center"。Program.Main()' C:''Users''logicwaves''Documents''Visual Studio 2005''Projects''center''center''Program.cs 13 21 center
3)错误 3 程序"C:''Users''logicwaves''Documents''Visual Studio 2005''Projects''center''center''obj''Debug''center.exe"定义了多个入口点:"CenterForm.Main()" C:''Users''logicwaves''Documents''Visual Studio 2005''Projects''center''center''Form1.cs 58 17 center
我应该怎么做才能克服这些错误?
不需要那个CenterForm.StartPosition = FormStartPosition.CenterScreen;
错误是因为您在 Form.cs 类中定义了Main()
方法。 通常,如果您使用的是Visual Studio,它将在Program.cs类中。 Dispose()
方法也可以在 Form.Designer 中使用.cs。您可以通过将 StartPosition
属性设置为 FormStartPosition.CenterScreen
来使屏幕的表单中心;
试试这个:
this
当前表单的含义
this.CenterToScreen();
1.在记事本中打开.cs文件
2.现在(ctr + A)全选并删除(看不到任何文本)
3.键入以下代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace **[Namespace of your form]**
{
public partial class [class name of your form]: Form
{
public [class name of your form]()
{
InitializeComponent();
}
}
}
它真的在工作...