简体   繁体   English

如何关闭窗体并打开另一个

[英]How to close form and open another

Currently learning to code in C#.目前正在学习用 C# 编写代码。 I have used the code我已经使用了代码

Form1.Hide();
Music_Menu.Show();

The names for the forms are correct and believe this should work but I get this error when I hover over the text:表单的名称是正确的,并且相信这应该可以工作,但是当我将鼠标悬停在文本上时出现此错误:

an object reference is required to access non static field member or property c#访问非静态字段成员或属性 c# 需要对象引用

I am betting that Music_Menu is the name of your form's class.我敢打赌 Music_Menu 是您的表单类的名称。

You need to create an INSTANCE of the form.您需要创建表单的实例。 VB did this "behind the scenes," but C# demands you get it right. VB 在“幕后”做到了这一点,但 C# 要求您做对。

Somewhere in Program.Main(), I'll bet you have a line:在 Program.Main() 的某个地方,我敢打赌你有一行:

Application.Run(new Form1());

You need to keep that reference.您需要保留该参考。 A private static field in the Program class should work. Program 类中的私有静态字段应该可以工作。

private static Form1 _myForm1;
private static Music_Menu _myMusic_Menu;

Then in the Main() method, change that to:然后在 Main() 方法中,将其更改为:

_myForm1 = new Form1();
Application.Run(_myForm1);

Then your code (where you switch) should be (in Program.cs):那么你的代码(你切换的地方)应该是(在 Program.cs 中):

_myForm1.Hide(); 
_myMusic_Menu = new Music_Menu();
_myMusic_Menu.Show();

Alternatively, if you want to run the code in Form1 (and assuming you want to come back to your instance of Form1:或者,如果您想在 Form1 中运行代码(并假设您想回到 Form1 的实例:

this.Hide();
var myMusic_Menu = new Music_Menu();
myMusic.ShowDialog();
this.Show();

You'll probably have some scope issues to straighten out depending on your context, but this should get you going in the right direction.根据您的上下文,您可能会有一些范围问题需要解决,但这应该会让您朝着正确的方向前进。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM