[C# 윈폼] TextBox, Button (텍스트박스, 버튼) Enter Key(엔터키) 이벤트 발생 하기


 

안녕하세요.

 

오늘은 C# 윈폼에서 TextBox 컨트롤에 문자를 입력하여 키보드로 엔터키를 입력했을 때, 버튼 클릭 이벤트가 발생하여 입력한 문자열을 메시지 박스로 출력 되게 끔 소스코드를 작성해 보도록 할게요.

 

오늘의 핵심은 Key 이벤트를 발생하는 방법입니다!^^

 

1. 윈폼 프로젝트 생성 및 버튼, 텍스트 박스 컨트롤 배치




 

저는 위와 같이 배치를 하였습니다.

 

이제 실제로 저 위의 텍스트 박스에 문자를 입력하고, 엔터 키를 눌렀을 때에 버튼 클릭이벤트가 발생하여 메시지 박스가 출력 되게 끔 소스코드를 작성해 볼게요.

소스 코드


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

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 EnterKey

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

 

            this.uiBtn_EnterKey.Click += uiBtn_EnterKey_Click;

            this.tb_txt.KeyDown += tb_KeyDown;

        }

 

        //Key Down 이벤트 발생 이벤트 핸들러

        private void tb_KeyDown(object sender, KeyEventArgs e)

        {

            //엔터키 이벤트 발생

            if (e.KeyCode == Keys.Enter)

            {

                uiBtn_EnterKey_Click(sender, e);

            }

        }

 

        private void uiBtn_EnterKey_Click(object sneder, EventArgs e)

        {

            string text = string.Empty;

 

            text = tb_txt.Text;

            string msg = string.Format("당신이 입력한 문자는 {0} 입니다.", text);

            MessageBox.Show(msg);

        }

    }

}

 

Colored by Color Scripter

cs


실행 결과



 

이처럼, TextBox 컨트롤에 범범조조 라는 문자를 입력하고, 엔터키를 눌렀을 때 메시지박스가 제대로 띄어지는 것을 확인할 수 있습니다.

 

감사합니다.^^


728x90

이 글을 공유하기

댓글

Designed by JB FACTORY