닫기 버튼을 클릭 할 때 닫는 대신 양식 숨기기
사용자 X가 양식 의 단추를 클릭 할 때 닫는 대신 숨기려면 어떻게해야합니까?
나는 시도 this.hide()
에 FormClosing
하지만 여전히 양식을 닫습니다.
이렇게 :
private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true;
Hide();
}
}
( Tim Huffman을 통해 )
나는 이전 답변에서 언급했지만 내 대답을 제공 할 것이라고 생각했습니다. 귀하의 질문에 따라이 코드는 상위 답변과 유사하지만 다른 언급 기능을 추가합니다.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true;
Hide();
}
}
사용자가 단순히 X창을 누르는 경우 양식이 숨겨집니다. 작업 관리자, Application.Exit()
또는 Windows 종료 와 같은 다른 항목이 있으면 return
명령문이 실행 되므로 양식이 제대로 닫힙니다 .
에서 MSDN :
양식 닫기를 취소하려면 이벤트 핸들러에 전달 된 의
Cancel
속성을로 설정합니다 .FormClosingEventArgs
true
그러니 취소하고 숨 깁니다.
표시 / 숨기기 방법을 사용하려면 내가 최근에 한 게임의 메뉴 구조에 대해 실제로 직접이 작업을 수행했습니다. 이것이 내가 한 방법입니다.
예를 들어 '다음'버튼과 같이 원하는 작업에 대한 버튼을 만들고 다음 코드를 프로그램에 일치시킵니다. 이 예제에서 다음 버튼의 코드는 다음과 같습니다.
btnNext.Enabled = true; //This enabled the button obviously
this.Hide(); //Here is where the hiding of the form will happen when the button is clicked
Form newForm = new newForm(); //This creates a new instance object for the new form
CurrentForm.Hide(); //This hides the current form where you placed the button.
다음은 제가 설명하려는 내용을 이해하는 데 도움이되도록 게임에서 사용한 코드의 일부입니다.
private void btnInst_Click(object sender, EventArgs e)
{
btnInst.Enabled = true; //Enables the button to work
this.Hide(); // Hides the current form
Form Instructions = new Instructions(); //Instantiates a new instance form object
Instructions.Show(); //Shows the instance form created above
}
따라서 간단한 작업을 위해 막대한 코드를 수행하는 대신 몇 줄의 코드 표시 / 숨기기 방법이 있습니다. 문제 해결에 도움이 되었기를 바랍니다.
이 작업을 수행 할 때 (여러 답변이 게시 됨) 사용자가 정말로 원할 때 양식을 닫을 수 있도록 허용하는 방법도 찾아야합니다. 이것은 (적어도 일부 OS에서는) OS가 적절하거나 효율적으로 종료되는 것을 막기 때문에 사용자가 응용 프로그램이 실행 중일 때 시스템을 종료하려고하면 실제로 문제가됩니다.
이 문제를 해결 한 방법은 스택 추적을 확인하는 것이 었습니다. 사용자가 클릭을 시도 할 X때와 시스템이 종료를 준비하기 위해 애플리케이션을 종료하려고 할 때 사이에 차이가 있습니다 .
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
StackTrace trace = new StackTrace();
StackFrame frame;
bool bFoundExitCommand = false;
for (int i = 0; i < trace.FrameCount; i++)
{
frame = trace.GetFrame(i);
string methodName = frame.GetMethod().Name;
if (methodName == "miExit_Click")
{
bFoundExitCommand = true;
Log("FormClosing: Found Exit Command ({0}) - will allow exit", LogUtilityLevel.Debug3, methodName);
}
if (methodName == "PeekMessage")
{
bFoundExitCommand = true;
Log("FormClosing: Found System Shutdown ({0}) - will allow exit", LogUtilityLevel.Debug3, methodName);
}
Log("FormClosing: frame.GetMethod().Name = {0}", LogUtilityLevel.Debug4, methodName);
}
if (!bFoundExitCommand)
{
e.Cancel = true;
this.Visible = false;
}
else
{
this.Visible = false;
}
}
This is the behavior of Modal forms. When you use form.ShowDialog()
you are asking for this behavior. The reason for this is that form.ShowDialog doesn't return until the form is hidden or destroyed. So when the form is hidden, the pump inside form.ShowDialog destroys it so that it can return.
If you want to show and hide a form, then you should be using the Modeless dialog model http://msdn.microsoft.com/en-us/library/39wcs2dh(VS.80).aspx
form.Show()
returns immediately, you can show and hide this window all you want and it will not be destroyed until you explicitly destroy it.
When you use modeless forms that are not children of a modal form, then you also need to run a message pump using Application.Run
or Application.DoEvents
in a loop. If the thread that creates a form exits, then the form will be destroyed. If that thread doesn't run a pump then the forms it owns will be unresponsive.
Edit: this sounds like the sort of thing that the ApplicationContext
is designed to solve. http://msdn.microsoft.com/en-us/library/system.windows.forms.applicationcontext.aspx
Basically, you derive a class from ApplicationContext, pass an instance of your ApplicationContext as an argument to Application.Run()
// Create the MyApplicationContext, that derives from ApplicationContext,
// that manages when the application should exit.
MyApplicationContext context = new MyApplicationContext();
// Run the application with the specific context.
Application.Run(context);
Your application context will need to know when it's ok to exit the application and when having the form(s) hidden should not exit the application. When it's time for the app to exit. Your application context or form can call the application context's ExitThread()
method to terminate the message loop. At that point Application.Run()
will return.
Without knowing more about the heirarchy of your forms and your rules for deciding when to hide forms and when to exit, it's impossible to be more specific.
Based on other response, you can put it in your form code :
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
if (e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true;
Hide();
}
}
The override is preferred: MSDN "The OnFormClosing method also allows derived classes to handle the event without attaching a delegate. This is the preferred technique for handling the event in a derived class. "
참고URL : https://stackoverflow.com/questions/2021681/hide-form-instead-of-closing-when-close-button-clicked
'developer tip' 카테고리의 다른 글
각도 필터를 조건부로 만들기 (0) | 2020.12.10 |
---|---|
WPF에서 중첩 요소 스타일 지정 (0) | 2020.12.10 |
iOS의 활동 수명주기에 해당하는 것은 무엇입니까? (0) | 2020.12.10 |
명령 줄에서 데이터베이스 만들기 (0) | 2020.12.10 |
ActivityCompat.requestPermissions가 대화 상자를 표시하지 않음 (0) | 2020.12.10 |