Windows Form에서 표준 닫기 (X) 단추 재정의
사용자가 Windows Forms 응용 프로그램 (C #)에서 닫기 (빨간색 X) 단추를 클릭 할 때 발생하는 작업을 변경하려면 어떻게해야합니까?
이를 위해 OnFormClosing 을 재정의 할 수 있습니다 . 닫기 위해 'X'를 클릭하는 것은 잘 알려진 동작이므로 예상치 못한 일을하지 않도록주의하십시오.
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
if (e.CloseReason == CloseReason.WindowsShutDown) return;
// Confirm user wants to close
switch (MessageBox.Show(this, "Are you sure you want to close?", "Closing", MessageBoxButtons.YesNo))
{
case DialogResult.No:
e.Cancel = true;
break;
default:
break;
}
}
OnFormClosing 메서드를 재정의합니다 .
주의 : CloseReason을 확인하고 UserClosing 인 경우에만 동작을 변경해야합니다. Windows 종료 루틴을 지연시킬 수있는 어떤 것도 여기에 넣어서는 안됩니다.
Windows Vista의 응용 프로그램 종료 변경 사항
이것은 Windows 7 로고 프로그램 요구 사항 에서 가져온 것 입니다.
이 답변이 부족하고 초보자가 찾고있는 한 가지는 이벤트가있는 것이 좋지만 다음과 같습니다.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// do something
}
이벤트 를 등록 하지 않으면 아무것도하지 않습니다 . 이것을 클래스 생성자에 넣으십시오.
this.FormClosing += Form1_FormClosing;
OnFormClosing을 재정의 하거나 FormClosing 이벤트에 등록하십시오 .
다음은 파생 양식에서 OnFormClosing 함수를 재정의하는 예입니다.
protected override void OnFormClosing(FormClosingEventArgs e)
{
e.Cancel = true;
}
다음은 모든 클래스에있을 수있는 양식이 닫히지 않도록하는 이벤트 처리기의 예입니다.
private void FormClosing(object sender,FormClosingEventArgs e)
{
e.Cancel = true;
}
고급을 얻으려면 FormClosingEventArgs에서 CloseReason 속성을 확인하여 적절한 작업이 수행되었는지 확인하십시오. 사용자가 양식을 닫으려고하는 경우에만 대체 작업을 수행 할 수 있습니다.
Jon B가 말했듯이, ApplicationExitCall
그리고 TaskManagerClosing
CloseReason도 확인 하고 싶을 것입니다.
protected override void OnFormClosing(FormClosingEventArgs e)
{
if ( e.CloseReason == CloseReason.WindowsShutDown
||e.CloseReason == CloseReason.ApplicationExitCall
||e.CloseReason == CloseReason.TaskManagerClosing) {
return;
}
e.Cancel = true;
//assuming you want the close-button to only hide the form,
//and are overriding the form's OnFormClosing method:
this.Hide();
}
OnFormClosing을 재정의 하시겠습니까 ?
x- 버튼 클릭 이벤트를 처리 할 수있는 것이 매우 유용한 한 가지 상황은 MDI 컨테이너 인 Form을 사용하는 경우입니다. 그 이유는 close 및 closed 이벤트가 먼저 자식에서 발생하고 마지막으로 부모와 함께 발생하기 때문입니다. 따라서 한 시나리오에서 사용자는 x 버튼을 클릭하여 응용 프로그램을 닫고 MDI 부모는 계속 진행하기 위해 확인을 요청합니다. 그가 신청서를 닫지 않고 그가하는 일을 계속하기로 결정한 경우, 아이들은 잠재적으로 정보 / 작업을 잃을 가능성이있는 마감 이벤트를 이미 처리했을 것입니다. 한 가지 해결책은 다음과 같이 기본 애플리케이션 양식 (즉, 애플리케이션이 닫히고 종료 됨)의 Windows 메시지 루프에서 WM_CLOSE 메시지를 가로채는 것입니다.
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x0010) // WM_CLOSE
{
// If we don't want to close this window
if (ShowConfirmation("Are you sure?") != DialogResult.Yes) return;
}
base.WndProc(ref m);
}
이것은 꽤 자주 묻는 질문입니다. 여기에 좋은 대답이 있습니다.
VB.NET overload default functionality when user clicks the X (Close Program)
If you don't feel comfortable putting your code in the Form_Closing event, the only other option I am aware of is a "hack" that I've used once or twice. It should not be necessary to resort to this hack, but here it is:
Don't use the normal close button. Instead, create your form so that it has no ControlBox. You can do this by setting ControlBox = false on the form, in which case, you will still have the normal bar across the top of the form, or you can set the form's FormBorderStyle to "None. If you go this second route, there will be no bar across the top, or any other visible border, so you'll have to simulate those either by drawing on the form, or by artistic use of Panel controls.
Then you can add a standard button and make it look like a close button, and put your clean-up code in there. At the end of the button event, just call this.Close()
(C#) or Me.Close()
(VB)
protected override bool ProcessCmdKey(ref Message msg, Keys dataKey)
{
if (dataKey == Keys.Escape)
{
this.Close();
//this.Visible = false;
//Plus clear values from form, if Visible false.
}
return base.ProcessCmdKey(ref msg, dataKey);
}
The accepted answer works quite well. An alternative method that I have used is to create a FormClosing method for the main Form. This is very similar to the override. My example is for an application that minimizes to the system tray when clicking the close button on the Form.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.ApplicationExitCall)
{
return;
}
else
{
e.Cancel = true;
WindowState = FormWindowState.Minimized;
}
}
This will allow ALT+F4 or anything in the Application calling Application.Exit(); to act as normal while clicking the (X) will minimize the Application.
참고URL : https://stackoverflow.com/questions/1669318/override-standard-close-x-button-in-a-windows-form
'Program Tip' 카테고리의 다른 글
디스플레이 없음없이 jQuery 페이드 아웃? (0) | 2020.10.28 |
---|---|
Excel에서 ISO8601 날짜 / 시간 (TimeZone 포함) 구문 분석 (0) | 2020.10.28 |
비대화 형으로 IPython / Jupyter 노트북 실행 (0) | 2020.10.27 |
"템플릿 <>"대 괄호없는 "템플릿"-차이점은 무엇입니까? (0) | 2020.10.27 |
Quartz.net을 ASP.NET과 함께 사용하는 방법 (0) | 2020.10.27 |