1 / 11

Mouse • A pointin g devic e wit h on e o r mor e buttons

This guide explores the mouse as an essential input device, detailing its functions, events, and programming implementations within Windows. It covers fundamental mouse actions like clicking, dragging, and double-clicking, as well as mouse events and handler methods defined by the Control class. Additionally, it discusses using C# to create interactive sketching applications, storing mouse movement data using ArrayLists, and managing sketches in memory. Learn how to effectively handle mouse events, capture input, and integrate mouse functionality in your applications.

dinah
Télécharger la présentation

Mouse • A pointin g devic e wit h on e o r mor e buttons

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. TheMouseandKeyboard Mouse •Apointingdevicewithoneormorebuttons •Importantinputdevice,butnotrequired •Usermovesphysicalmouse=> –Windowsmovesasmallbitmappedimage(mousecursor)ondisplaydevice –"Hotspot"pointstoapreciselocationondisplay –Hotspotpositionconstantlyupdatedbylow-levellogicinsideWindows

  2. MouseActions •ButtonDown,ButtonUp •Wheelmovement •Movingmouse •Clicking –Pressingandreleasingamousebutton •Dragging –Movingmousewhileabuttonispresseddown •DoubleClicking –Clickingabuttontwiceinsuccession –Mustoccurwithinasetperiodoftimeandwithmousecursorinapproximatelythesameplace •Form’sSystemInformationclasshastwopropertiesthatgivethisinformation: –intDoubleClickTime –SizeDoubleClickSize InformationaboutMouse •MoreofForm’sSystemInformationProperties: –boolMousePresent –intMouseButtons •Getsnumberofmousebuttononthemouse –boolMouseButtonsSwapped –boolMouseWheelPresent

  3. 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

  4. 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

  5. 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:

  6. 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

  7. 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

  8. 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

  9. 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

  10. 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)

  11. TwoExamplePrograms •Key: –Assemblesincomingcharactersfromkeyboardintoastringthatisdisplayedontheform'sclientarea •HandlesBackspacekeybyremovinglastcharacterfromstring –HandlesKeyPressevent •KeyArrow: –Movesanimageontheform'sclientareainresponsetokeyboardLeft/Right/Up/Downarrowkeypresses –HandlesKeyDownevent

More Related