我是 C# 的新手。
下面是我试图在代码中创建表单和容器的代码;但我有问题。
- 我从一个新的
Windows 窗体应用程序模板开始。 - 我稍微更改了
Program.cs文件,以便能够动态创建FormMain。 - 当
FormMain.cs中的Container.Add(BtnClose)和BtnClose_Setup()行被注释时,代码编译并运行。但是,程序中还是出现了一些奇怪的结果。
(a) 表单 FormMain 应该显示在 (20, 20)(左上角),如 FormMain_Setup 所说;但是当我运行该应用程序时,虽然宽度和高度设置按预期显示 (800、600),但左上角每次都会发生变化(不坚持 20、20)。
(b) esc 键按预期工作并关闭表单和应用程序。
- 当
FormMain.cs中的Container.Add(BtnClose)和BtnClose_Setup()行不注释,代码编译但 VS 在运行时向我发送一条消息:“mscorlib.dll 中发生类型为‘System.TypeInitializationException’的未处理异常”
谁能告诉我我做错了什么?
Program.cs 文件:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace test {
static class Program {
public static FormMain FormMain = new FormMain();
[STAThread]
static void Main() {
Application.Run(FormMain);
}
}
}
FormMain.cs 文件:
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;
namespace test {
public partial class FormMain : Form {
Button BtnClose = new Button();
public void BtnClose_Setup() {
BtnClose.Text = "Ok";
BtnClose.Top = 500;
BtnClose.Left = 700;
}
public void FormMain_Setup() {
Top = 20;
Left = 20;
Width = 800;
Height = 600;
KeyDown += FormMain_KeyDown;
//Container.Add(BtnClose);
//BtnClose_Setup();
}
void FormMain_KeyDown(object sender, KeyEventArgs e) {
if(e.KeyCode == Keys.Escape) {
Close();
}
}
public FormMain() {
InitializeComponent();
FormMain_Setup();
}
}
}
请您参考如下方法:
调用 Controls.Add(BtnClose); 而不是 Container.Add(BtnClose);。
固定窗体位置:设置StartPosition = FormStartPosition.Manual;属性。
要在 Esc 上正确关闭表单,请覆盖 ProcessCmdKey 方法:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Escape)
{
Close();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
