[C#] Add KeyListener to non-form class.

Discussion in 'Mixed Languages' started by Stannieman, May 16, 2013.

  1. Stannieman

    Stannieman MDL Guru

    Sep 4, 2009

    For school we need to make the first round of the Belgian tv game "Blokken".
    2 players are asked a question and if they know the answer they need to press a button as fast as possible.
    If the fastest player answers correctly then he plays 2 pieces in a tetrisgame.

    What I have now is a form that first makes an object of the TetrisGame class (which creates a tetrisboard with pieces and all the tetris logic).
    The form then asks a question and listens for keys (each player has it's own key). The handler is in the form class.
    Then the player can play tetris.
    What I can do is let the form handle the keyevents and call the right functions of the tetrisgame object. (dirty)
    A second possibility is to switch the handler to a handler in the tetrisgame class to handle the events while playing (good but still a bit dirty).

    What seems the cleanest is to let the tetrisgame class have it's own KeyEventListener. So the TetrisGame object itself recieves the keystrokes and not the form. Is this somehow possible or can keylisteners only be added to objects inherited from the Form class (or Console)?

    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...

    PAYMYRENT MDL Developer

    Jul 28, 2009
    Good Sir you are asking for a keyboard hook. or a hotkey in a wndproc for the main form you can then have the wndproc call upon the handler in your tetris class
  3. stevemk14ebr

    stevemk14ebr MDL Senior Member

    Jun 23, 2010
    for recieving global keyboard presses you have a few simple options the easiest but dirtiest is the Getasynckeystate api (very easy) or you could make a global keyboard hook, or you could use the windows hotkey api, i recomend the keyboard hook personally
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...