c # 새 양식을 연 다음 현재 양식을 닫으시겠습니까?
예를 들어, 내가 양식 1에 있다고 가정하면 다음을 원합니다.
- 양식 2 열기 (양식 1의 단추에서)
- 양식 1 닫기
- 양식 2에 집중
Steve의 솔루션이 작동하지 않습니다. this.Close ()를 호출하면 현재 폼이 form2와 함께 삭제됩니다. 따라서이를 숨기고 form2.Closed 이벤트를 설정하여 this.Close ()를 호출해야합니다.
private void OnButton1Click(object sender, EventArgs e)
{
this.Hide();
var form2 = new Form2();
form2.Closed += (s, args) => this.Close();
form2.Show();
}
이렇게 해보세요 ...
{
this.Hide();
Form1 sistema = new Form1();
sistema.ShowDialog();
this.Close();
}
다른 답변은 이미 많은 다른 방법을 설명했습니다. 그러나 그들 중 많은 사람들이 관련 ShowDialog()
되거나 form1
열려 있지만 숨겨져 있습니다. 내 생각에 가장 직관적이고 가장 직관적 인 방법은 단순히 닫은 form1
다음 form2
외부 위치에서 생성 하는 것입니다. 경우 form1
에 생성 된 Main
, form2
간단하게 사용하여 만들 수 있습니다 Application.Run
처럼 form1
전에. 다음은 예제 시나리오입니다.
어떻게 든 인증하려면 사용자가 자격 증명을 입력해야합니다. 이후 인증이 성공하면 메인 애플리케이션을 사용자에게 보여주고 싶습니다. 이를 수행하기 위해 두 가지 형식을 사용 LogingForm
하고 MainForm
있습니다 : 및 . 에 LoginForm
인증의 성공 여부를 결정하는 플래그가 있습니다. 이 플래그는 MainForm
인스턴스 를 만들지 여부를 결정하는 데 사용됩니다 . 이 두 양식 모두 다른 양식에 대해 알 필요가 없으며 두 양식 모두 정상적으로 열고 닫을 수 있습니다. 이에 대한 코드는 다음과 같습니다.
class LoginForm : Form
{
bool UserSuccessfullyAuthenticated { get; private set; }
void LoginButton_Click(object s, EventArgs e)
{
if(AuthenticateUser(/* ... */))
{
UserSuccessfullyAuthenticated = true;
Close();
}
}
}
static class Program
{
[STAThread]
static void Main()
{
LoginForm loginForm = new LoginForm();
Application.Run(loginForm);
if(loginForm.UserSuccessfullyAuthenticated)
{
// MainForm is defined elsewhere
Application.Run(new MainForm());
}
}
}
그 라인의 문제 존재 :
Application.Run(new Form1());
program.cs 파일에서 찾을 수 있습니다.
이 줄은 form1이 메시지 루프를 처리한다는 것을 나타냅니다. 즉, form1이 응용 프로그램을 계속 실행하는 책임이 있습니다. form1이 닫히면 응용 프로그램이 닫힙니다.
이를 처리하는 방법에는 여러 가지가 있지만 모두 어떤 방식 으로든 form1을 닫지 않습니다.
(프로젝트 유형을 Windows Forms 응용 프로그램 이외의 것으로 변경하지 않는 한)
내가 생각하기에 가장 쉬운 방법은 3 가지 양식을 만드는 것입니다.
form1-표시되지 않고 관리자 역할을하며 원하는 경우 트레이 아이콘을 처리하도록 지정할 수 있습니다.
form2-버튼을 클릭하면 form2가 닫히고 form3이 열립니다.
form3-열어야하는 다른 양식의 역할을 갖습니다.
다음은이를 수행하는 샘플 코드입니다.
(또한 세 번째 양식에서 앱을 닫는 예제를 추가했습니다)
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1()); //set the only message pump to form1.
}
}
public partial class Form1 : Form
{
public static Form1 Form1Instance;
public Form1()
{
//Everyone eveywhere in the app should know me as Form1.Form1Instance
Form1Instance = this;
//Make sure I am kept hidden
WindowState = FormWindowState.Minimized;
ShowInTaskbar = false;
Visible = false;
InitializeComponent();
//Open a managed form - the one the user sees..
var form2 = new Form2();
form2.Show();
}
}
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var form3 = new Form3(); //create an instance of form 3
Hide(); //hide me (form2)
form3.Show(); //show form3
Close(); //close me (form2), since form1 is the message loop - no problem.
}
}
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1.Form1Instance.Close(); //the user want to exit the app - let's close form1.
}
}
참고 : 패널로 작업하거나 사용자 컨트롤을 동적으로로드하는 것이 산업 생산 표준으로 더 학문적이고 선호됩니다.하지만이 예제가 더 나은 목적을 위해 작동 방식을 추론하려는 것 같습니다.
이제 원칙이 이해되었으므로 두 가지 형식으로 시도해 보겠습니다.
첫 번째 양식은 이전 예에서와 같이 관리자 역할을 맡지 만 첫 번째 화면도 표시하므로 닫히지 않고 숨겨집니다.
두 번째 양식은 다음 화면을 표시하는 역할을하며 버튼을 클릭하면 애플리케이션이 닫힙니다.
public partial class Form1 : Form
{
public static Form1 Form1Instance;
public Form1()
{
//Everyone eveywhere in the app show know me as Form1.Form1Instance
Form1Instance = this;
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//Make sure I am kept hidden
WindowState = FormWindowState.Minimized;
ShowInTaskbar = false;
Visible = false;
//Open another form
var form2 = new Form2
{
//since we open it from a minimezed window - it will not be focused unless we put it as TopMost.
TopMost = true
};
form2.Show();
//now that that it is topmost and shown - we want to set its behavior to be normal window again.
form2.TopMost = false;
}
}
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1.Form1Instance.Close();
}
}
이전 예제를 변경하는 경우-프로젝트에서 form3을 삭제하십시오.
행운을 빕니다.
구체적이지는 않았지만 Win Forms 앱에서 내가하는 일을하려고했던 것 같습니다. 로그인 양식으로 시작한 다음 성공적인 로그인 후 해당 양식을 닫고 기본 양식에 초점을 두십시오. 방법은 다음과 같습니다.
frmMain을 시작 양식으로 만듭니다. 이것은 내 Program.cs의 모습입니다.
[STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmMain()); }
내 frmLogin에서 성공적인 로그인이 발생한 경우에만 false로 초기화되고 true로 설정되는 공용 속성을 만듭니다.
public bool IsLoggedIn { get; set; }
내 frmMain은 다음과 같습니다.
private void frmMain_Load(object sender, EventArgs e) { frmLogin frm = new frmLogin(); frm.IsLoggedIn = false; frm.ShowDialog(); if (!frm.IsLoggedIn) { this.Close(); Application.Exit(); return; }
로그인에 성공하지 못했습니까? 응용 프로그램을 종료하십시오. 그렇지 않으면 frmMain으로 계속하십시오. 시작 양식이므로 닫히면 응용 프로그램이 종료됩니다.
이 코드 조각을 form1에서 사용하십시오.
public static void ThreadProc()
{
Application.Run(new Form());
}
private void button1_Click(object sender, EventArgs e)
{
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc));
t.Start();
this.Close();
}
나는 여기 에서 이것을 얻었다
두 가지 양식이있는 경우 : frm_form1 및 frm_form2. 다음 코드는 frm_form2를 열고 frm_form1을 닫는 데 사용됩니다. (Windows 양식 응용 프로그램의 경우)
this.Hide();//Hide the 'current' form, i.e frm_form1
//show another form ( frm_form2 )
frm_form2 frm = new frm_form2();
frm.ShowDialog();
//Close the form.(frm_form1)
this.Close();
Suppose you have two Form, First Form Name is Form1 and second form name is Form2.You have to jump from Form1 to Form2 enter code here. Write code like following:
On Form1 I have one button named Button1, and on its click option write below code:
protected void Button1_Click(Object sender,EventArgs e)
{
Form frm=new Form2();// I have created object of Form2
frm.Show();
this.Visible=false;
this.Hide();
this.Close();
this.Dispose();
}
Hope this code will help you
private void buttonNextForm(object sender, EventArgs e)
{
NextForm nf = new NextForm();//Object of the form that you want to open
this.hide();//Hide cirrent form.
nf.ShowModel();//Display the next form window
this.Close();//While closing the NextForm, control will come again and will close this form as well
}
//if Form1 is old form and Form2 is the current form which we want to open, then
{
Form2 f2 = new Form1();
this.Hide();// To hide old form i.e Form1
f2.Show();
}
This code may help you:
Master frm = new Master();
this.Hide();
frm.ShowDialog();
this.Close();
this.Visible = false;
//or // will make LOgin Form invisivble
//this.Enabled = false;
// or
// this.Hide();
Form1 form1 = new Form1();
form1.ShowDialog();
this.Dispose();
I think this is much easier :)
private void btnLogin_Click(object sender, EventArgs e)
{
//this.Hide();
//var mm = new MainMenu();
//mm.FormClosed += (s, args) => this.Close();
//mm.Show();
this.Hide();
MainMenu mm = new MainMenu();
mm.Show();
}
I would solve it by doing:
private void button1_Click(object sender, EventArgs e)
{
Form2 m = new Form2();
m.Show();
Form1 f = new Form1();
this.Visible = false;
this.Hide();
}
참고URL : https://stackoverflow.com/questions/5548746/c-sharp-open-a-new-form-then-close-the-current-form
'Program Tip' 카테고리의 다른 글
Swift- 푸시 알림 배지 번호를 제거 하시겠습니까? (0) | 2020.11.09 |
---|---|
RequireJS : 단일 "클래스"를 포함하는 모듈을 정의하는 방법은 무엇입니까? (0) | 2020.11.09 |
PyCharm이 Python 파일을 인식하지 못함 (0) | 2020.11.09 |
내 getter 메서드가 저장된 값을 변경하도록하는 것이 나쁜 습관입니까? (0) | 2020.11.09 |
디렉터리에서 최신 파일을 복사하는 Windows 배치 스크립트를 어떻게 작성합니까? (0) | 2020.11.09 |