About Monkey 2 › Forums › Monkey 2 Code Library › KeyboardMapper (to map ui.Buttion with KeyEvent)
This topic contains 1 reply, has 1 voice, and was last updated by
nerobot 1 year, 4 months ago.
-
AuthorPosts
-
December 4, 2017 at 12:16 pm #12109
Originally, I wrote similar code as an answer for unity3d. Use it or lose it!
Idea is: we have some ui.Buttons and want to click them by keyboard with breaking nothing.
And we can do it using KeyboardMapper. Just write single line and voila!
_mapper.Map( but,Key.S,Modifier.Control )
but is mojox.Button here.
You can add only one key combunation per button.
You can specify what types of key events to grab; default types are KeyDown & KeyRepeat.
You’ll find KeyboardMapper class in the example app below:
Monkey123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128#Import "<std>"#Import "<mojo>"#Import "<mojox>"Using std..Using mojo..Using mojox..Function Main()New AppInstanceNew MyWindowApp.Run()EndClass MyWindow Extends WindowMethod New()Super.New( "KeyboardMapper example",640,480,WindowFlags.Resizable )Local but:=New Button( "Save" )but.Layout="float"but.Gravity=New Vec2f( .5 )but.Clicked=Lambda()Alert( "Save was clicked" )EndContentView=but' map our button with Ctrl+S_mapper.Map( but,Key.S,Modifier.Control )EndPrivateField _mapper:=New KeyboardMapper<Button>EndClass KeyboardMapper<T> Where T Extends mojox.ButtonClass ItemField button:TField key:KeyField modifiers:ModifierEndMethod New( types:EventType[]=New EventType[]( EventType.KeyDown,EventType.KeyRepeat ) )_types=typesApp.KeyEventFilter+=UpdateEndOperator []:Item( button:T )Return _items[button]EndOperator []=( button:T,key:Key )Map( button,key )EndOperator -=( button:T )Unmap( button )EndMethod Map( button:T,key:Key,modifiers:Modifier=Modifier.None )Local i:=_items[button]If Not ii=New Itemi.button=button_items[button]=iEndifi.key=keyi.modifiers=modifiersEndMethod Unmap( button:T )_items.Remove( button )EndPrivateField _items:=New Map<T,Item>Field _types:EventType[]Method Update( event:KeyEvent )If Not CheckEvent( event ) ReturnLocal key:=event.KeyLocal modif:=event.ModifiersFor Local i:=Eachin _items.ValuesIf i.key=key And modif & i.modifiers <> 0i.button.Clicked()' ExitEndifNextEndMethod CheckEvent:Bool( event:KeyEvent )For Local i:=Eachin _typesIf event.Type=i Return TrueNextReturn FalseEndEndDecember 4, 2017 at 12:25 pm #12110Actually, we can to omit where condition, and then we can pass any instance with method Clicked() as a button – thanks to geteric type T.
-
AuthorPosts
You must be logged in to reply to this topic.