C#
C# Form Shortcut - 폼에 단축키 지정하기
J-sean
2021. 11. 25. 22:01
반응형
버튼이나 다른 컨트롤이 있는 폼에서 특정 키를 눌렀을때 원하는 동작을 하게 하기 위해 Form KeyDown 이벤트 핸들러를 작성해도 포커스를 갖고 있는 컨트롤이 먼저 키 이벤트를 처리하기 때문에 원하는 동작을 처리할 수 없다.
폼이 먼저 이벤트를 받기 위해서는 KeyPreview 프로퍼티를 true로 설정해야 한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//button1.TabStop = false;
//button2.TabStop = false;
// TabStop = false로 하면 처음엔 제대로 작동하는거 같지만
// 버튼을 한 번 클릭하고 나서는 버튼이 계속 포커스를 갖기
// 때문에 제대로 작동하지 않는다.
// Gets or sets a value indicating whether the form will
// receive key events before the event is passed to the
// control that has focus.
// true if the form will receive all key events;
// false if the currently selected control on the form
// receives key events. The default is false.
// 키가 눌렸을때 포커스를 갖고 있는 컨트롤보다 폼이 먼저
// 키 이벤트를 받을 수 있게 한다.
KeyPreview = true;
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Button1");
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show("Button2");
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.F1:
MessageBox.Show("F1");
break;
default:
break;
}
}
}
}
|
반응형