在C#表单中我需要代码将第二个表单添加到现有表单中。这就是我尝试过的:
第一种形式:
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
frmMain fM = new frmMain();
fM.KeyPress += new KeyPressEventHandler(MMForm);
}
private void MMForm(object sender, KeyPressEventArgs e)
{
Keys KP; KP = (Keys)sender;
if (KP == Keys.Escape) { frm2 fM2 = new frm2(); fM2.Show(); }
}
}
这是第二种形式:
public class frm2 : Form
{
public frm2()
{
frm2 fM2 = new frm2();
fM2.Height = 200; fM2.Width = 200;
Controls.AddRange(new System.Windows.Forms.Form[] { fM2 });
}
}
我错过了什么?
编辑:暂时忘掉这一切。即使我按照建议那样按下按键也会出错。An unhandled exception of type 'System.InvalidCastException' occurred in Project 09.exe
Additional information: Specified cast is not valid.
答案 0 :(得分:1)
private void frmMain_Load(object sender, EventArgs e)
{
frmMain fM = new frmMain();
fM.KeyPress += new KeyPressEventHandler(MMForm);
}
替换为:
private void frmMain_Load(object sender, EventArgs e)
{
this.KeyPress += new KeyPressEventHandler(MMForm);
}
或者您可以通过设计师直接注册到自己的KeyPress,直接注册到MMForm ......
而且,目前还不清楚你在这里要做什么:
public frm2()
{
frm2 fM2 = new frm2();
fM2.Height = 200; fM2.Width = 200;
Controls.AddRange(new System.Windows.Forms.Form[] { fM2 });
}
应该看起来更像这样:
public frm2()
{
InitializeComponents();
this.Height = 200;
this.Width = 200;
}
即使您不想使用InitializeComponents,也应该编辑自己的(this)属性,而不是新的frm2属性。 您在frmMain_Load中遇到了同样的问题,当您创建了一个新的frmMain,并订阅了它的KeyPress时,您真的应该订阅自己的KeyPress。
另外,你可以缩短你的MMForm只是为了美化,如下:
private void MMForm(object sender, KeyPressEventArgs e)
{
if ((Keys)sender == Keys.Escape)
{
new frm2().Show();
}
}
答案 1 :(得分:1)
你应该使用代码belove作为你现有的表格(如果你不调整表格的话,请在属性中设置它的权重。
public class frm2 : Form
{
public frm2()
{
InitializeComponent(); ,
this.Width = 200; this.Height = 200;
}
}
如果你想显示frm2,那么在特殊键之后:
frm2 secondFrom = new frm2();
frm2.Show(); // frm2.ShowDialog(); works too but they are working differently.
答案 2 :(得分:1)
你可以这样做:
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
this.private void MMForm(object sender, KeyPressEventArgs e)
}
private void MMForm(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == Convert.ToChar(((int)Keys.Escape)))
{
frm2 fM2 = new frm2(); fm2.Height=200; fm2.Width=200; fM2.Show();
}
}
public class frm2 : Form
{
public frm2()
{
InitializeComponent();
}
}
答案 3 :(得分:1)
如果在主窗体上按下转义键时尝试打开frm2,请执行以下操作:
public frmMain()
{
InitializeComponent();
this.KeyPress += new KeyPressEventHandler(MMForm);
}
//You don't need to put anything in form load
private void frmMain_Load(object sender, EventArgs e)
{
}
//This is fine
private void MMForm(object sender, KeyPressEventArgs e)
{
Keys KP; KP = (Keys)sender;
if (KP == Keys.Escape) { frm2 fM2 = new frm2(); fM2.Show(); }
}
在frm2中执行:
public class frm2 : Form
{
public frm2()
{
InitializeComponent();
this.Height = 200; this.Width = 200;
Controls.AddRange(new System.Windows.Forms.Form[] { fM2 });
}
}