Share via


방법: 표준 컨트롤로 키보드 입력 수정

Windows Forms는 키보드 입력을 사용 및 수정할 수 있는 기능을 제공합니다. 키 사용은 메시지 큐 아래의 다른 메서드 및 이벤트가 키 값을 수신하지 않도록 메서드 또는 이벤트 처리기 내에서 키를 처리하는 것을 가리킵니다. 키 수정은 메시지 큐 아래의 메서드 및 이벤트 처리기가 다른 키 값을 수신하도록 키 값을 수정하는 것을 가리킵니다. 이 항목에서는 이러한 작업을 수행하는 방법을 보여 줍니다.

키를 사용하려면

  • KeyPress 이벤트 처리기에서 KeyPressEventArgs 클래스의 Handled 속성을 true로 설정합니다.

    또는

    KeyDown 이벤트 처리기에서 KeyEventArgs 클래스의 Handled 속성을 true로 설정합니다.

    참고

    KeyDown 이벤트 처리기에서 Handled 속성을 설정해도 KeyPressKeyUp 이벤트가 현재 키 입력에 대해 발생하지 않도록 차단되지는 않습니다. 이렇게 하려면 SuppressKeyPress 속성을 사용합니다.

    다음 예제는 KeyPress 이벤트 처리기가 수신한 KeyPressEventArgsKeyChar 속성을 검사하는 switch 문에서 발췌한 내용입니다. 이 코드는 'A' 및 'a' 문자 키를 사용합니다.

    // Consume 'A' and 'a'.
    case (char)65:
    case (char)97:
        MessageBox.Show("Control.KeyPress: '" +
            e.KeyChar.ToString() + "' consumed.");
        e.Handled = true;
        break;
    
    ' Consume 'A' and 'a'.
    Case ChrW(65), ChrW(97)
        MessageBox.Show(("Control.KeyPress: '" + _
            e.KeyChar.ToString() + "' consumed."))
        e.Handled = True
    

표준 문자 키를 수정하려면

  • KeyPress 이벤트 처리기에서 KeyPressEventArgs 클래스의 KeyChar 속성을 새 문자 키의 값으로 설정합니다.

    다음 예제는 'B'를 'A’로 수정하고 'b'를 'a'로 수정하는 switch 문에서 발췌한 내용입니다. 새로운 키 값이 메시지 큐의 다른 메서드 및 이벤트에 전파되도록 KeyPressEventArgs 매개 변수의 Handled 속성은 false로 설정됩니다.

    // Detect 'B', modify it to 'A', and forward the key.
    case (char)66:
        MessageBox.Show("Control.KeyPress: '" +
            e.KeyChar.ToString() + "' replaced by 'A'.");
        e.KeyChar = (char)65;
        e.Handled = false;
        break;
    
    // Detect 'b', modify it to 'a', and forward the key.
    case (char)98:
        MessageBox.Show("Control.KeyPress: '" +
            e.KeyChar.ToString() + "' replaced by 'a'.");
        e.KeyChar = (char)97;
        e.Handled = false;
        break;
    
        ' Modify 'B' to 'A' and forward the key.
    Case ChrW(66)
        MessageBox.Show(("Control.KeyPress: '" + _
            e.KeyChar.ToString() + "' replaced by 'A'."))
        e.KeyChar = ChrW(65)
        e.Handled = False
    
        ' Modify 'b' to 'a' and forward the key.
    Case ChrW(98)
        MessageBox.Show(("Control.KeyPress: '" + _
            e.KeyChar.ToString() + "' replaced by 'a'."))
        e.KeyChar = ChrW(97)
        e.Handled = False
    

문자가 아닌 키를 수정하려면

  • Windows 메시지를 처리하는 Control 메서드를 재정의하고, WM_KEYDOWN 또는 WM_SYSKEYDOWN 메시지를 검색하고, Message 매개 변수의 WParam 속성을 문자가 아닌 새 키를 나타내는 Keys 값으로 설정합니다.

    다음 코드 예제에서는 컨트롤의 PreProcessMessage 메서드를 재정의하여 F1-F9 키를 검색하고 F3 키 누름을 F1로 수정하는 방법을 보여 줍니다. 키보드 메시지를 가로채기 위해 재정의할 수 있는 Control 메서드에 대한 자세한 내용은 Windows Forms 애플리케이션의 사용자 입력키보드 입력 작동 방식을 참조하세요.

    // Detect F1 through F9 during preprocessing and modify F3.
    public override bool PreProcessMessage(ref Message m)
    {
        if (m.Msg == WM_KEYDOWN)
        {
            Keys keyCode = (Keys)m.WParam & Keys.KeyCode;
    
            // Detect F1 through F9.
            switch (keyCode)
            {
                case Keys.F1:
                case Keys.F2:
                case Keys.F3:
                case Keys.F4:
                case Keys.F5:
                case Keys.F6:
                case Keys.F7:
                case Keys.F8:
                case Keys.F9:
    
                    MessageBox.Show("Control.PreProcessMessage: '" +
                      keyCode.ToString() + "' pressed.");
    
                    // Replace F3 with F1, so that ProcessKeyMessage will
                    // receive F1 instead of F3.
                    if (keyCode == Keys.F3)
                    {
                        m.WParam = (IntPtr)Keys.F1;
                        MessageBox.Show("Control.PreProcessMessage: '" +
                            keyCode.ToString() + "' replaced by F1.");
                    }
                    break;
            }
        }
    
        // Send all other messages to the base method.
        return base.PreProcessMessage(ref m);
    }
    
    ' Detect F1 through F9 during preprocessing and modify F3.
    Public Overrides Function PreProcessMessage(ByRef m As Message) _
        As Boolean
    
        If m.Msg = WM_KEYDOWN Then
            Dim keyCode As Keys = CType(m.WParam, Keys) And Keys.KeyCode
    
            ' Detect F1 through F9.
            Select Case keyCode
                Case Keys.F1, Keys.F2, Keys.F3, Keys.F4, Keys.F5, _
                     Keys.F6, Keys.F7, Keys.F8, Keys.F9
    
                    MessageBox.Show(("Control.PreProcessMessage: '" + _
                        keyCode.ToString() + "' pressed."))
    
                    ' Replace F3 with F1, so that ProcessKeyMessage will  
                    ' receive F1 instead of F3.
                    If keyCode = Keys.F3 Then
                        m.WParam = CType(Keys.F1, IntPtr)
                        MessageBox.Show(("Control.PreProcessMessage: '" + _
                            keyCode.ToString() + "' replaced by F1."))
                    End If
            End Select
        End If
    
        ' Send all other messages to the base method.
        Return MyBase.PreProcessMessage(m)
    End Function
    

예제

다음 코드 예제는 이전 섹션의 코드 예제에 대한 전체 애플리케이션입니다. 애플리케이션은 TextBox 클래스에서 파생된 사용자 지정 컨트롤을 통해 키보드 입력을 사용 및 수정합니다.

using System;
using System.Drawing;
using System.Windows.Forms;

namespace KeyboardInput
{
    class Form1 : Form
    {
        // The following Windows message value is defined in Winuser.h.
        private int WM_KEYDOWN = 0x100;
        CustomTextBox CustomTextBox1 = new CustomTextBox();

        [STAThread]
        public static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }

        public Form1()
        {
            this.AutoSize = true;
            this.Controls.Add(CustomTextBox1);
            CustomTextBox1.KeyPress +=
                new KeyPressEventHandler(CustomTextBox1_KeyPress);
        }

        // Consume and modify several character keys.
        void CustomTextBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            switch (e.KeyChar)
            {
                // Consume 'A' and 'a'.
                case (char)65:
                case (char)97:
                    MessageBox.Show("Control.KeyPress: '" +
                        e.KeyChar.ToString() + "' consumed.");
                    e.Handled = true;
                    break;

                // Detect 'B', modify it to 'A', and forward the key.
                case (char)66:
                    MessageBox.Show("Control.KeyPress: '" +
                        e.KeyChar.ToString() + "' replaced by 'A'.");
                    e.KeyChar = (char)65;
                    e.Handled = false;
                    break;

                // Detect 'b', modify it to 'a', and forward the key.
                case (char)98:
                    MessageBox.Show("Control.KeyPress: '" +
                        e.KeyChar.ToString() + "' replaced by 'a'.");
                    e.KeyChar = (char)97;
                    e.Handled = false;
                    break;
            }
        }
    }
    
    public class CustomTextBox : TextBox
    {
        // The following Windows message value is defined in Winuser.h.
        private int WM_KEYDOWN = 0x100;

        public CustomTextBox()
        {
            this.Size = new Size(100, 100);
            this.AutoSize = false;
        }

        // Detect F1 through F9 during preprocessing and modify F3.
        public override bool PreProcessMessage(ref Message m)
        {
            if (m.Msg == WM_KEYDOWN)
            {
                Keys keyCode = (Keys)m.WParam & Keys.KeyCode;

                // Detect F1 through F9.
                switch (keyCode)
                {
                    case Keys.F1:
                    case Keys.F2:
                    case Keys.F3:
                    case Keys.F4:
                    case Keys.F5:
                    case Keys.F6:
                    case Keys.F7:
                    case Keys.F8:
                    case Keys.F9:

                        MessageBox.Show("Control.PreProcessMessage: '" +
                          keyCode.ToString() + "' pressed.");

                        // Replace F3 with F1, so that ProcessKeyMessage will
                        // receive F1 instead of F3.
                        if (keyCode == Keys.F3)
                        {
                            m.WParam = (IntPtr)Keys.F1;
                            MessageBox.Show("Control.PreProcessMessage: '" +
                                keyCode.ToString() + "' replaced by F1.");
                        }
                        break;
                }
            }

            // Send all other messages to the base method.
            return base.PreProcessMessage(ref m);
        }

        // Detect F1 through F9 during processing.
        protected override bool ProcessKeyMessage(ref Message m)
        {
            if (m.Msg == WM_KEYDOWN)
            {
                Keys keyCode = (Keys)m.WParam & Keys.KeyCode;

                // Detect F1 through F9.
                switch (keyCode)
                {
                    case Keys.F1:
                    case Keys.F2:
                    case Keys.F3:
                    case Keys.F4:
                    case Keys.F5:
                    case Keys.F6:
                    case Keys.F7:
                    case Keys.F8:
                    case Keys.F9:

                        MessageBox.Show("Control.ProcessKeyMessage: '" +
                          keyCode.ToString() + "' pressed.");
                        break;
                }
            }

            // Send all messages to the base method.
            return base.ProcessKeyMessage(ref m);
        }
    }
}
Imports System.Drawing
Imports System.Security
Imports System.Security.Permissions
Imports System.Windows.Forms

Namespace KeyboardInput
    Class Form1
        Inherits Form

        ' The following Windows message value is defined in Winuser.h.
        Private WM_KEYDOWN As Integer = &H100
        Private WithEvents CustomTextBox1 As New CustomTextBox()

        <STAThread()> _
        Public Shared Sub Main()
            Application.EnableVisualStyles()
            Application.Run(New Form1())
        End Sub

        Public Sub New()
            Me.AutoSize = True
            Me.Controls.Add(CustomTextBox1)
        End Sub

        ' Consume and modify several character keys.
        Sub CustomTextBox1_KeyPress(ByVal sender As Object, _
            ByVal e As KeyPressEventArgs) Handles CustomTextBox1.KeyPress

            Select Case e.KeyChar

                ' Consume 'A' and 'a'.
                Case ChrW(65), ChrW(97)
                    MessageBox.Show(("Control.KeyPress: '" + _
                        e.KeyChar.ToString() + "' consumed."))
                    e.Handled = True

                    ' Modify 'B' to 'A' and forward the key.
                Case ChrW(66)
                    MessageBox.Show(("Control.KeyPress: '" + _
                        e.KeyChar.ToString() + "' replaced by 'A'."))
                    e.KeyChar = ChrW(65)
                    e.Handled = False

                    ' Modify 'b' to 'a' and forward the key.
                Case ChrW(98)
                    MessageBox.Show(("Control.KeyPress: '" + _
                        e.KeyChar.ToString() + "' replaced by 'a'."))
                    e.KeyChar = ChrW(97)
                    e.Handled = False
            End Select
        End Sub
    End Class

    Public Class CustomTextBox
        Inherits TextBox

        ' The following Windows message value is defined in Winuser.h.
        Private WM_KEYDOWN As Integer = &H100

        Public Sub New()
            Me.Size = New Size(100, 100)
            Me.AutoSize = False
        End Sub

        ' Detect F1 through F9 during preprocessing and modify F3.
        Public Overrides Function PreProcessMessage(ByRef m As Message) _
            As Boolean

            If m.Msg = WM_KEYDOWN Then
                Dim keyCode As Keys = CType(m.WParam, Keys) And Keys.KeyCode

                ' Detect F1 through F9.
                Select Case keyCode
                    Case Keys.F1, Keys.F2, Keys.F3, Keys.F4, Keys.F5, _
                         Keys.F6, Keys.F7, Keys.F8, Keys.F9

                        MessageBox.Show(("Control.PreProcessMessage: '" + _
                            keyCode.ToString() + "' pressed."))

                        ' Replace F3 with F1, so that ProcessKeyMessage will  
                        ' receive F1 instead of F3.
                        If keyCode = Keys.F3 Then
                            m.WParam = CType(Keys.F1, IntPtr)
                            MessageBox.Show(("Control.PreProcessMessage: '" + _
                                keyCode.ToString() + "' replaced by F1."))
                        End If
                End Select
            End If

            ' Send all other messages to the base method.
            Return MyBase.PreProcessMessage(m)
        End Function

        ' Detect F1 through F9 during processing.
        Protected Overrides Function ProcessKeyMessage(ByRef m As Message) _
            As Boolean

            If m.Msg = WM_KEYDOWN Then
                Dim keyCode As Keys = CType(m.WParam, Keys) And Keys.KeyCode

                ' Detect F1 through F9.
                Select Case keyCode
                    Case Keys.F1, Keys.F2, Keys.F3, Keys.F4, Keys.F5, _
                         Keys.F6, Keys.F7, Keys.F8, Keys.F9

                        MessageBox.Show(("Control.ProcessKeyMessage: '" + _
                            keyCode.ToString() + "' pressed."))
                End Select
            End If

            ' Send all messages to the base method.
            Return MyBase.ProcessKeyMessage(m)
        End Function

    End Class
End Namespace

코드 컴파일

이 예제에는 다음 사항이 필요합니다.

  • System, System.Drawing 및 System.Windows.Forms 어셈블리에 대한 참조

참고 항목