我想要2个类(1个Form类) 在表单类中,我将Another Class称为void。有用 我想用标签和文本框(在第二类脚本中)做thigs 我看到了How to change a label from another class? c# windows forms visual studio 和我的代码:
`private new void Enter(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == Convert.ToChar(Keys.Enter))
{
Commands.OnCommand();`
其他课程:
public static void OnCommand()
{
Form1 frm = new Form1();
if (frm.code.Text.Contains("end") && frm.code.TextLength == 4)
{
if (MessageBox.Show("Close?", "Close window?", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
frm.Close();
}
else
{
frm.output.Text = (frm.output.Text + "\nClosing closed").ToString();
frm.code.Clear();
}
}
else
{
MessageBox.Show("test");
frm.output.Text = (frm.output.Text + "\nI don't understand ... ").ToString();
frm.code.Clear();
} /**/
它只显示消息框 ....我认为错误在于声明form1
答案 0 :(得分:2)
您必须传递对原始表单的引用,而不是创建它的新实例:
private new void Enter(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == Convert.ToChar(Keys.Enter))
{
Commands.OnCommand(this);
public static void OnCommand(Form1 frm)
{
if (frm.code.Text.Contains("end") && frm.code.TextLength == 4)
{
话虽如此,我认为将整个Form的引用发送到另一种方法是不好的做法。相反,尝试重新构建它,以便只传入方法所需的值(如code.Text
),并让它返回表单需要显示的值。
private new void Enter(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == Convert.ToChar(Keys.Enter))
{
string message = Commands.OnCommand(code.Text);
if (message == "")
{
Close();
}
else
{
frm.output.Text = frm.output.Text + message;
frm.code.Clear();
}
public static void OnCommand(string code)
{
if (code.Contains("end") && code.Length == 4)
{
if (MessageBox.Show("Close?", "Close window?", MessageBoxButtons.YesNo) == DialogResult.Yes)
return "";
else
return "Closing closed";
}
else
{
MessageBox.Show("test");
return "I don't understand ... ";
}