2009-05-24 3 views
7

Microsoft Visual C# 2008 Express를 사용하고 있습니다.C# 폼의 종료 버튼에 코드를 추가하려면 어떻게해야합니까?

내 기본 양식에는 오른쪽 상단의 양식을 닫는 X 버튼이 있습니다. 이 단추에 코드를 추가하려면 어떻게합니까? 내 메뉴에는 "Exit"항목이 있고 데이터베이스를 정리하고 닫는 코드가 있습니다. 사용자가 종료 방법으로 이것을 선택하면이 단추에 동일한 코드를 어떻게 추가합니까?

감사합니다.

- 아데나

답변

12

FormClosing 이벤트를 사용하면 양식을 닫는 방법을 포착해야합니다.

0

winform의 폐쇄 이벤트를 사용하십시오.

+0

를 호출 한 후 을 form'design에서 종료 버튼을 클릭하는 것은입니다 "FormClosed"또는 "FormClosing" ? 또는 내가하고있는 모든 것이 데이터베이스를 닫는 것과 같은 것이면 상관 없다 ...? – adeena

+0

죄송합니다, 오타 : 폐막식을 의미했습니다. 하지만 그저 .NET 2.0의 FormClosed-Event로 대체되었다고 읽었습니다. –

7

양식의 디자인보기에서 속성 창 내에서 이벤트 단추를 선택하고 "FormClosed"및 "FormClosing"이벤트까지 스크롤하십시오.

FormClosed는 양식을 닫은 후에 호출됩니다.

FormClosing는 양식이 폐쇄되기 전에 호출 또한 개방 형태를 유지, 당신은 가까운을 취소 할 수 있습니다 :

private void Form1_FormClosing(object sender, FormClosingEventArgs e) 
{ 
    e.Cancel = true; 
} 
0

FormClosing/FormClosed 응용 프로그램과 일치 수 형태의 이벤트를 볼 수 있습니다 종료. 그러나 Application.ApplicationExit이라는 다른 이벤트가 있습니다. 자신의 메인 방법에서

:

Application.ApplicationExit += Application_ApplicationExit; 

... 

private static void Application_ApplicationExit(object sender, EventArgs e) { 

    // do stuff when the application is truly exiting, regardless of the reason 

} 
0

이 코드는 당신이 뭔가를 할 수 있도록하기 위해 'X'또는 양식에 Alt 키-F4 사용에 대한 사용자의 클릭을 캡처합니다. 나는 이것을 사용했다. 왜냐하면 나는 closing 이벤트를 호출하는 액션이 ​​필요했기 때문에, 레이싱 이벤트로 인해 FormClosing 이벤트를 사용할 때 호출하지 않을 것이다. 당신이 사용자에게 물어보고 싶은 경우

/// <summary> 
/// This code captures the 'Alt-F4' and the click to the 'X' on the ControlBox 
/// and forces it to call MyClose() instead of Application.Exit() as it would have. 
/// This fixes issues where the threads will stay alive after the application exits. 
/// </summary> 
public const int SC_CLOSE = 0xF060; 
public const int WM_SYSCOMMAND = 0x0112; 
protected override void WndProc(ref System.Windows.Forms.Message m) 
{ 
    if (m.Msg == WM_SYSCOMMAND && (int)m.WParam == SC_CLOSE) 
     MyClose(); 

    base.WndProc(ref m); 
} 
1

"당신은 당신이이 양식을 가까이 할 하시겠습니까?", 당신은 Cancel = True을 설정할 수, FormClosing를 사용하여 양식이 열린 상태를 유지합니다.

양식이 완전히 닫힌 경우에만 자원을 닫으려면 FormClosed 이벤트를 사용하십시오.

전체 코드를 제어하는 ​​경우 문제가되지 않습니다. 그러나 이벤트의 다른 핸들러가 양식을 열어 둘 때 FormClosing을 사용하여 자원을 정리하는 것이 바람직하지 않습니다.

0

더블 단순히

0

양식 액션 메소드에게 폐기() 메소드에게 //

protected override void OnFormClosing(FormClosingEventArgs e) 

      { 
      base.OnFormClosing(e); 

      if (e.CloseReason == CloseReason.WindowsShutDown) return; 

       switch (MessageBox.Show(this, "Are you sure you want to exit?", "Exit", MessageBoxButtons.YesNo)) 
        { 
         case DialogResult.No: 
          e.Cancel = true; 
          break; 
        default: 
          break; 
        } 
     } 
0
You can use form closing events choose or set closing event in properties window  
You can add dialog conditions based on what task you want to perform before closing form 

private void Form1_FormClosing(object sender,FormClosingEventArgs e) 
{ 
Application.Exit(); 
//you can also use Application.ExitThread(); 
} 
관련 문제