Programing

위쪽, 아래쪽, 왼쪽 및 오른쪽 화살표 키는 KeyDown 이벤트를 트리거하지 않습니다.

lottogame 2020. 11. 14. 09:46
반응형

위쪽, 아래쪽, 왼쪽 및 오른쪽 화살표 키는 KeyDown 이벤트를 트리거하지 않습니다.


모든 키 입력이 창 자체에서 처리되어야하는 응용 프로그램을 만들고 있습니다.

각 컨트롤 마녀가 패널을 제외하고 포커스를 잡을 수 있도록 tabstop을 false로 설정했습니다 (하지만 효과가 있는지는 모르겠습니다).

KeyPreview를 true로 설정하고이 양식에서 KeyDown 이벤트를 처리하고 있습니다.

내 문제는 때때로 화살표 키가 더 이상 반응하지 않는다는 것입니다.

  • 화살표 키만 누르면 keydown 이벤트가 시작되지 않습니다.

  • 컨트롤 수정 자로 화살표 키를 누르면 keydown 이벤트가 시작됩니다.

내 화살표 키가 갑자기 이벤트 실행을 중지하는 이유를 알고 있습니까?


    protected override bool IsInputKey(Keys keyData)
    {
        switch (keyData)
        {
            case Keys.Right:
            case Keys.Left:
            case Keys.Up:
            case Keys.Down:
                return true;
            case Keys.Shift | Keys.Right:
            case Keys.Shift | Keys.Left:
            case Keys.Shift | Keys.Up:
            case Keys.Shift | Keys.Down:
                return true;
        }
        return base.IsInputKey(keyData);
    }
    protected override void OnKeyDown(KeyEventArgs e)
    {
        base.OnKeyDown(e);
        switch (e.KeyCode)
        {
            case Keys.Left:
            case Keys.Right:
            case Keys.Up:
            case Keys.Down:
                if (e.Shift)
                {

                }
                else
                {
                }
                break;                
        }
    }

나는 똑같은 문제를 겪고 있었다. @Snarfblam이 제공 한 답변을 고려했습니다. 그러나 MSDN의 설명서를 읽으면 ProcessCMDKey 메서드는 응용 프로그램의 메뉴 항목에 대한 키 이벤트를 재정의하기위한 것입니다.

나는 최근에 Microsoft에서이 기사를 우연히 발견했습니다. http://msdn.microsoft.com/en-us/library/system.windows.forms.control.previewkeydown.aspx . 마이크로 소프트에 따르면, 할 수있는 가장 좋은 방법은 설정 e.IsInputKey=true;에서 PreviewKeyDown화살표 키를 감지 한 후 이벤트. 그렇게하면 KeyDown이벤트가 시작됩니다.

이것은 나를 위해 꽤 잘 작동했으며 ProcessCMDKey를 재정의하는 것보다 덜 해킹 적이었습니다.


PreviewKeyDown을 사용하고 있습니다.

    private void _calendar_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e){
        switch (e.KeyCode){
            case Keys.Down:
            case Keys.Right:
                //action
                break;
            case Keys.Up:
            case Keys.Left:
                //action
                break;
        }
    }

베스트 답변 Rodolfo Neuber의 답변참조하십시오.


(내 원래 답변) :

컨트롤 클래스에서 파생되고 ProcessCmdKey 메서드를 재정의 할 수 있습니다. Microsoft는 여러 컨트롤에 영향을 미치고 포커스를 이동하기 때문에 KeyDown 이벤트에서 이러한 키를 생략하기로 결정했지만, 이로 인해 앱이 다른 방식으로 이러한 키에 반응하도록 만들기가 매우 어렵습니다.


불행히도 KeyDown 이벤트의 제한으로 인해 화살표 키로이를 수행하는 것은 매우 어렵습니다. 그러나이 문제를 해결할 수있는 몇 가지 방법이 있습니다.

  • @Snarfblam이 언급했듯이 화살표 키 누름을 구문 분석하는 기능을 유지하는 ProcessCmdKey 메서드를 재정의수 있습니다 .
  • As the accepted answer from this question states, XNA has a built-in method called Keyboard.GetState(), which allows you to use arrow key inputs. However, WinForms doesn't have this, but it can be done through a P/Invoke, or by using a class that helps with it.

I recommend trying to use that class. It's quite simple to do so:

var left = KeyboardInfo.GetKeyState(Keys.Left);
var right = KeyboardInfo.GetKeyState(Keys.Right);
var up = KeyboardInfo.GetKeyState(Keys.Up);
var down = KeyboardInfo.GetKeyState(Keys.Down);

if (left.IsPressed)
{
//do something...
}

//etc...

If you use this in combination with the KeyDown event, I think you can reliably accomplish your goal.


I had a similar issue when calling the WPF window out of WinForms.

var wpfwindow = new ScreenBoardWPF.IzbiraProjekti();
    ElementHost.EnableModelessKeyboardInterop(wpfwindow);
    wpfwindow.Show();

However, showing window as a dialog, it worked

var wpfwindow = new ScreenBoardWPF.IzbiraProjekti();
    ElementHost.EnableModelessKeyboardInterop(wpfwindow);
    wpfwindow.ShowDialog();

Hope this helps.


In order to capture keystrokes in a Forms control, you must derive a new class that is based on the class of the control that you want, and you override the ProcessCmdKey().

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    //handle your keys here
}

Example :

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    //capture up arrow key
    if (keyData == Keys.Up )
    {
        MessageBox.Show("You pressed Up arrow key");
        return true;
    }

    return base.ProcessCmdKey(ref msg, keyData);
}

Full source...Arrow keys in C#

Vayne


The best way to do, I think, is to handle it like the MSDN said on http://msdn.microsoft.com/en-us/library/system.windows.forms.control.previewkeydown.aspx

But handle it, how you really need it. My way (in the example below) is to catch every KeyDown ;-)

    /// <summary>
    /// onPreviewKeyDown
    /// </summary>
    /// <param name="e"></param>
    protected override void OnPreviewKeyDown(PreviewKeyDownEventArgs e)
    {
        e.IsInputKey = true;
    }

    /// <summary>
    /// onKeyDown
    /// </summary>
    /// <param name="e"></param>
    protected override void OnKeyDown(KeyEventArgs e)
    {
        Input.SetFlag(e.KeyCode);
        e.Handled = true;
    }

    /// <summary>
    /// onKeyUp
    /// </summary>
    /// <param name="e"></param>
    protected override void OnKeyUp(KeyEventArgs e)
    {
        Input.RemoveFlag(e.KeyCode);
        e.Handled = true;
    }

i had the same problem and was already using the code in the selected answer. this link was the answer for me; maybe for others also.

How to disable navigation on WinForm with arrows in C#?


protected override bool IsInputKey(Keys keyData)
{
    if (((keyData & Keys.Up) == Keys.Up)
        || ((keyData & Keys.Down) == Keys.Down)
        || ((keyData & Keys.Left) == Keys.Left)
        || ((keyData & Keys.Right) == Keys.Right))
        return true;
    else
        return base.IsInputKey(keyData);
}

참고URL : https://stackoverflow.com/questions/1646998/up-down-left-and-right-arrow-keys-do-not-trigger-keydown-event

반응형