문제

좋아, 그래서 나는 C#을 배우는 데 도움이되는 Tic-Tac-Toe 게임을 만드는 과정에 있습니다. 나는 약간의 기능을 추가하려고 시도하고 있으므로 사람들이 컴퓨터에서 나머드를 사용하여 버튼을 클릭하는 것을 시뮬레이션 할 수 있기를 원합니다.

여기에 내가 가진 것이 있지만 Numpad를 사용하면 버튼을 클릭하지 않습니다. 왜 그런지에 대한 이유를 볼 수 있습니까?

    //===============================
    // start NumPad Simulate Clicks
    //   NumPad  MyButtons
    //   7 8 9   1 2 3
    //   4 5 6   4 5 6 
    //   1 2 3   7 8 9
    //===============================
    public void myControl_NumPad7(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)Keys.NumPad7)
        {
            button1_Click(null, null);
        }
    }
    public void myControl_NumPad8(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)Keys.NumPad8)
        {
            button2_Click(null, null);
        }
    }
    public void myControl_NumPad9(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)Keys.NumPad9)
        {
            button3_Click(null, null);
        }
    }
    public void myControl_NumPad4(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)Keys.NumPad4)
        {
            button4_Click(null, null);
        }
    }
    public void myControl_NumPad5(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)Keys.NumPad5)
        {
            button5_Click(null, null);
        }
    }
    public void myControl_NumPad6(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)Keys.NumPad6)
        {
            button6_Click(null, null);
        }
    }
    public void myControl_NumPad1(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)Keys.NumPad1)
        {
            button7_Click(null, null);
        }
    }
    public void myControl_NumPad2(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)Keys.NumPad2)
        {
            button8_Click(null, null);
        }
    }
    public void myControl_NumPad3(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)Keys.NumPad3)
        {
            button9_Click(null, null);
        }
    }
도움이 되었습니까?

해결책

편집하다
내가 의미하는 바에 대해 더 명확해야한다는 것을 알아 차렸다 ...

게시 한 코드에서 키 이벤트를 추가 한 9 개의 컨트롤이 있다고 생각합니다. 이러한 컨트롤은 키 이벤트가 집중할 때만받습니다.

양식을 위해 전 세계적으로 키를 처리하려면 설정해야합니다. Form.KeyPreview 에게 true. 또한, 나는 당신이하는 방식대로 키를 처리하지는 않지만 추가 Form.KeyDown 이벤트 및 다음과 같은 글을 쓰십시오.

switch (e.KeyCode)
{
    case Keys.NumPad9:
        e.Handled = true;
        button3.PerformClick();
        break;
    case Keys.NumPad8:
        e.Handled = true;
        button2.PerformClick();
        break;
    // And so on
}

이것은 양식 내에서 Numpad -Keys를 처리합니다. 그런 다음 질문에 게시 한 모든 이벤트 핸들러를 제거 할 수 있습니다.

프로그래밍 방식으로 "클릭"버튼을 사용하려면 사용해야합니다. Button.PerformClick() 메소드는 하나 이상의 이벤트 핸들러가 클릭 이벤트에 추가 될 수 있으므로 그렇지 않으면 호출되지 않습니다.

편집 2
에 대한 구문 switch-진술은 유효하지 않았습니다. 물론 모든 "케이스"는 case 키워드 ... 이제 작동해야합니다.

다른 팁

사용해야합니다 button1.PerformClick(); 모든 버튼이 이벤트를 올바르게 호출하려면 여기에 정보.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top