110 likes | 221 Views
The Mouse and Keyboard. Mouse • A pointin g devic e wit h on e o r mor e buttons • Importan t inpu t device , bu t no t required • Use r move s physica l mous e = > – Window s move s a smal l bitmappe d imag e (mouse cursor ) o n displa y device
E N D
TheMouseandKeyboard Mouse •Apointingdevicewithoneormorebuttons •Importantinputdevice,butnotrequired •Usermovesphysicalmouse=> –Windowsmovesasmallbitmappedimage(mousecursor)ondisplaydevice –"Hotspot"pointstoapreciselocationondisplay –Hotspotpositionconstantlyupdatedbylow-levellogicinsideWindows
MouseActions •ButtonDown,ButtonUp •Wheelmovement •Movingmouse •Clicking –Pressingandreleasingamousebutton •Dragging –Movingmousewhileabuttonispresseddown •DoubleClicking –Clickingabuttontwiceinsuccession –Mustoccurwithinasetperiodoftimeandwithmousecursorinapproximatelythesameplace •Form’sSystemInformationclasshastwopropertiesthatgivethisinformation: –intDoubleClickTime –SizeDoubleClickSize InformationaboutMouse •MoreofForm’sSystemInformationProperties: –boolMousePresent –intMouseButtons •Getsnumberofmousebuttononthemouse –boolMouseButtonsSwapped –boolMouseWheelPresent
MouseEvents –The“Control”Classdefines9mouseeventsand9correspondingprotectedeventhandlermethods •FormclassisderivedfromControlclass –Onlyonecontrolorformreceivesmouseevents •TheonethathasitsEnabledandVisiblepropertiessettotrue •Ifmultiplecontrolsarestacked,theenabledvisiblecontrolontopreceivestheevent –AFormobjectreceivesmouseeventsonlywhenmouseisoveritsclientarea •Butmousecanbe“captured”byacontrol--soitcanreceivemouseeventswhenmouseisnotoverit SomeBasicMouseEventsand HandlerMethods •MouseDownOnMouseDown() •MouseUpOnMouseUp() •MouseMoveOnMouseMove() •MouseWheelOnMouseWheel() –Delegateforeachevent:MouseEventHandler –2ndargumentforeachhandler:MouseEventArgs •ClickOnClick() •DoubleClickOnDoubleClick() –Delegateforeachevent:EventHandler –2ndargumentforeachhandler:EventArgs
MouseEventArgsProperty •Givesaccesstoread-onlypropertiesthat comewithmouseevents –intXHorizontalpositionofmouse –intYVerticalpositionofmouse –MouseButtonsButton •MouseButtonsenumerationpossibilities: –None,Left,Right,Middle »e.g.,MouseButtons.Left –Indicateswhichbuttonorbuttonsarecurrentlypressed –Eachbuttoncorrespondstoabitset •Exampleuse: –If(e.Button==MouseButtons.Left){//Dosomething} Click/DoubleClickEventArgs StaticProperties •Giveaccesstostatic,read-onlypropertiesthat comewithmouseClickandDoubleClickevents –PointMousePosition •Resultinscreencoordinates •Toconverttoclientareacoordinates,usePointToClient() –MouseButtonsMouseButtons •Returnswhichbuttonsarecurrentlypressed
SketchingExampleProgram •Sketch-dotNet –Sketchingrevisited •UsingC#andthe.NETFrameworkClassLibrary •Butifwindowisexposed,thesketchdisappears •Twowaystoavoidthis: 1.SavethepointsineachsketchandredrawalllinesegmentsinresponsetoPaintevent 2.Drawthesketchonashadowbitmapthattheprogramdrawsonwhileit’sdrawingonthescreen –ThenredrawthebitmapinresponsetoPaintevent SavingtheSketchpoints –Point[]apts=newPoint[?????] •Buthowbig? •BettertouseaC#dynamic“ArrayList” –AclassdefinedinSystem.Collectionsnamespace •Alsohasdatastructuresclasseslike:Queue,Stack,SortedList,HashTable –TocreateanewArrayList: •ArrayListarrlst=newArrayList(); –Couldholdanydatatype(s) –Toaddelements,e.g.,aPointp: •arrlst.Add(p); •CanalsoInsert()andRemove()elements –Accessinganelement:useanindexerasforanordinaryarray •Pointp=(Point)arrlst[2]; •Notetypecast –NeededbecauseindexerreturnsanobjectoftypeObject –NumberofobjectsinanArraylist:arrlst.Count •Coulduseanarray:
NewSketch-dotNetusinganArrayList •Asingleruncanhavemanysketches –Oneforeachtimeleftmousebuttongoesdown –SouseoneArrayListtostorethepointsforeachsketch •Whenfinished(whenmousebuttongoesup),converttoanarrayofPoints –UseasecondArrayListtostorethearrayofpointsforeachsketch(i.e.,an ArrayListofsketches) •MouseDownevent�startanewsketch'sArrayList •MouseMoveevent�drawlinesegmentandaddthepointtocurrentsketch'sArrayList •MouseUpevent�convertcurrentArrayListofpointstoanarrayofpoints&addittotheArrayListofsketches •Paintevent�useDrawLines(…)todrawallthelinesegmentsineachArrayList g.DrawLines(Penpen,Point[]a_pts);//a_ptsisanarrayofPoints •SeeSketch-dotNet-ArrayListexampleprogram –Herewe'rereallystoringthedrawinginaMetafileformat NewSketch-dotNetusingaShadow Bitmap •Storethewindowclientareaasashadowbitmap –Drawontheshadowbitmapandonthescreenwhenmousemoveswithitsleftbuttondown –DrawtheshadowbitmaponthethescreenwhenaPainteventoccurs –Notethatwiththistechniquealloftheinformationontheoriginalpointsislost •SeetheSketch-dotNet-Bitmapexampleprogram
SomeOtherMouseEventsand EventHandlers •MouseEnterOnMouseEnter() –Mousecursorhasbeenmovedontoform'sclientarea •MouseLeaveOnMouseLeave() –Mousecursorisnolongerontopofclientarea •MouseHoverOnMouseHover() –Mousecursorhasenteredclientareaandhasstoppedmoving –OnlyhappensoncebetweenMouseEnterand MouseLeaveevents •Delegateforeach:EventHandler •Argumentforeach:EventArgs •SeeMouse-Enter-Leave-Hoverexampleprogram TheMouseCursor •Alittlebitmaponscreenthatindicatesthelocationofthemouse •Canchangeitsappearance •Encapsulatedinthe‘Cursor'classdefinedin System.Windows.Forms •Getamousecursorfromthe‘Cursors'class –Consistsof28staticread-onlypropertiesthatreturnpredefinedobjectsoftype‘Cursor',e.g.: •Arrow,Cross,Default,Hand,Help,Ibeam,WaitCursor,etc. •SomeStaticread/writePropertiesof‘Cursor'class: –CursorCurrent –PointPosition –Forexampletodisplaythehourglasscursorontheform: •Cursor.Current=Cursors.WaitCursor; •SomeStaticCursormethods: –Show();Hide(); •SeeMouseCursorsexampleprogram
TheKeyboard •AsharedresourceinWindows –Allapplicationsreceiveinputfromsamekeyboard –Butanykeystrokehasasingledestination •Thedestinationisalwaysa‘Control'(e.g.aForm) –Objectthatreceivesakeyboardeventhasthe“inputfocus” –theactiveForm •Usuallythetopmostform •Ifformhasacaptionbar,itishighlighted –Form.ActiveFormstaticpropertyreturnstheactiveform –this.Activate()methodcanbeusedtomakethisformtheactiveform KeysandCharacters •Thinkofkeyboardintwoways: –Acollectionofdistinctphysicalkeys •Codegeneratedbyakeypressorreleaseidentifiesthekey –Ameansofgeneratingcharactercodes •Codegeneratedidentifiesacharacterinacharacterset –Traditionally8-bitASCIIcode –InWindows,extendedto16-bitUnicode –Keyboardcombinations(Shift,etc.)takenintoaccount
TypesofKeys •Keyboarddividedintofourgeneralgroupsofkeys –Togglekeys:Pressingkeychangesstate •CapsLock,NumLock,ScrollLock,Insert –Modifierkeys:Pressingkeyaffectsinterpretationofotherkeys •Shift,Ctrl,Alt –Non-characterkeys:Notassociatedwithdisplayable characters;directaprogramtocarryoutcertainactions •Functionkeys,PgUp,PgDn,Home,End,Insert,Delete,Arrow keys –Characterkeys:Letters,numbers,symbolkeys,spacebar,Backspace,Tabkey •GenerateASCII/Unicodecodeswhenpressed KeyboardEvents&Data •KeyDown,KeyEventArgs –Whenanykeyispressed(WM_KEYDOWN) •KeyPress,KeyPressEventArgs –Whenacharacter-generatingkeyispressed(WM_CHAR) –OccursafteraKeyDownevent •KeyUp,KeyEventArgs –Whenanykeyisreleased(WM_KEYUP) •NoteKeyUp/KeyDownandKeyPresseventdataisdifferent –KeyUp/KeyDowneventsprovidelow-levelinformationaboutthekeystroke–whichkey –KeyPressprovidesthecharactercode •Keyboardcombinationstakencareof
KeyDown/KeyUpEvents •KeyEventArgsProperties –KeyCodeIdentifieswhichkey –ModifiersIdentifiesshiftstates –KeyDataCombinesKeyCode&Modifiers •Keys:ahugeenumeration,someexamples: –Keys.A,Keys.Z,Keys.D0(zerokey),Keys.F1,Keys.Add, Keys.Home,Keys.Left,Keys.Back,Keys.Space,Keys.LShiftKey –SeeOnlineHelpon“Keysenumeration” –boolShiftTrueifShiftkeyispressed –boolAltTrueifAltkeyispressed –boolHandledSetbyeventhandler(initiallyfalse) –intKeyValueReturnsKeyDataasaninteger KeyPressEvent •Whenkey(s)pressedcorrespondtocharacter codes •KeyPressEventArgsProperties: –charKeyCharUnicode/ASCIIcharactercode –boolHandledSetbyhandler(initiallyfalse)
TwoExamplePrograms •Key: –Assemblesincomingcharactersfromkeyboardintoastringthatisdisplayedontheform'sclientarea •HandlesBackspacekeybyremovinglastcharacterfromstring –HandlesKeyPressevent •KeyArrow: –Movesanimageontheform'sclientareainresponsetokeyboardLeft/Right/Up/Downarrowkeypresses –HandlesKeyDownevent