C #에서 Windows Forms 양식을 닫는 Esc 단추
나는 다음을 시도했다 :
private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if ((Keys) e.KeyValue == Keys.Escape)
this.Close();
}
하지만 작동하지 않습니다.
그런 다음 이것을 시도했습니다.
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (e.KeyCode == Keys.Escape)
this.Close();
}
그리고 여전히 아무것도 작동하지 않습니다.
내 Windows Forms 양식 속성의 KeyPreview가 true로 설정되어 있습니다 ... 내가 뭘 잘못하고 있니?
이는 적절한 이벤트 핸들러 할당, KeyPreview, CancelButton 등에 관계없이 항상 작동합니다.
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if (keyData == Keys.Escape) {
this.Close();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
양식의 CancelButton
속성을 취소 버튼 으로 설정하면 코드가 필요하지 않습니다.
"취소"단추가 있다고 가정하면 양식의 CancelButton
속성 (디자이너 또는 코드)을 설정하면이 작업이 자동으로 처리됩니다. Click
버튼 이 발생할 경우 닫을 코드를 배치하기 만하면됩니다 .
받아 들여지는 대답은 실제로 정확하며 그 접근 방식을 여러 번 사용했습니다. 갑자기 더 이상 작동하지 않아서 이상하다는 것을 알았습니다. 대부분 내 중단 점이 ESC키에 대해 적중되지 않고 다른 키에 대해 적중되기 때문입니다.
디버깅 후 내 양식의 컨트롤 중 하나 ProcessCmdKey
가 다음 코드로 메서드 를 재정의한다는 것을 알았습니다 .
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
// ...
if (keyData == (Keys.Escape))
{
Close();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
... 그리고 이것은 내 양식이 ESC키 를 얻지 못하게 막았습니다 ( return true
). 따라서 자녀 컨트롤이 귀하의 입력을 차지하지 않도록하십시오.
양식 옵션에서 KeyPreview를 true로 설정 한 다음 여기에 Keypress 이벤트를 추가합니다. 키 누르기 이벤트에서 다음을 입력합니다.
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 27)
{
Close();
}
}
key.Char == 27
ASCII 코드의 이스케이프 값입니다.
By Escape button do you mean the Escape key? Judging by your code I think that's what you want. You could also try Application.Exit(), but Close should work. Do you have a worker thread? If a non-background thread is running this could keep the application open.
You need add this to event "KeyUp".
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Escape)
{
this.Close();
}
}
You can also Trigger some other form.
E.g. trigger a Cancel-Button if you edit the Form CancelButton property and set the button Cancel.
In the code you treath the Cancel Button as follows to close the form:
private void btnCancel_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Abort;
}
참고URL : https://stackoverflow.com/questions/2290959/escape-button-to-close-windows-forms-form-in-c-sharp
'IT story' 카테고리의 다른 글
바이트에서 특정 비트 가져 오기 (0) | 2020.09.10 |
---|---|
Symfony2 컨트롤러에서 JSON 응답을 어떻게 보낼 수 있습니까? (0) | 2020.09.10 |
Linux 커널은 어떻게 자체적으로 컴파일 할 수 있습니까? (0) | 2020.09.10 |
RatingBar를 만들어 별 다섯 개를 표시하는 방법 (0) | 2020.09.10 |
PHPExcel에서 배경 셀 색상 설정 (0) | 2020.09.10 |