Tải bản đầy đủ - 0 (trang)
Chapter 6.  Mouse and Keyboard Input

Chapter 6.  Mouse and Keyboard Input

Tải bản đầy đủ - 0trang

Chapter6.MouseandKeyboardInput

Thischaptercoversmouseandkeyboardinputandthe

smart-deviceequivalents.Mousesandkeyboardsare

standardinputdevicesonadesktopPCsystem,butno

standardexistsforsmart-deviceinput.Thereis,

instead,awiderangeofavailableinputhardware,

limitedonlybytheimaginationsoftheplatform

developmentteams.Programmerswhoarenewto

smart-deviceprogrammingneedtoadoptnew

approachestothinkingaboutuserinputwhen

developingsoftwareforsmartdevices.

Somesmartdeviceshaveamouse—oranequivalent,like

thetouchscreenonthePocketPC.Otherdeviceshaveno

pointingdevice;forexample,theSmartphonehasneither

mousenortouchscreen.Thesedifferencesinhardware

meanthatyouwillreceivedifferenttypesofinputoneach

ofthesedevices.

Somesmartdeviceshaveakeyboard—oranequivalent.

SomecustomCEdevices,forexample,haveacomplete

alphanumerickeyboard.PocketPCsdonothavea

hardwarekeyboard,buttheon-screenSoftwareInput

Panel(SIP)allowsinputofcharacterdata.[1]Thekeyboard

onaSmartphonehasaphonekeypadplusafewcommand

inputkeys.Astheseexamplesshow,theavailable

methodsforgettingcharacterdatavarywidely.

[1]YoucanconnectexternalkeyboardstovariousPocketPCs,somefromthedevice

manufacturerandothersfromthirdparties.Wewrotesomeofthetextforthisbook,in

fact,usinganexternalkeyboardwithaPocketPC.



Weusethetermsmouseandkeyboardinthischapterto

refertoanyinputdevicethatprovidesthesametypeof

input—pointingorcharacterkeyinput—asadesktop



device.

Amazon



Prev



don'tbeafraidofbuyingbooks



OverviewofInput

MostWindowsCE–powereddevicesdonothavethesameinput

hardwarefoundondesktopPCs.ConsideraPocketPC,whichhasa

touch-sensitivescreenforpointingandanon-screenSIPforcharacter

input.SomePocketPCshavenavigationkeys,theequivalentofarrow

keys(up,down,left,andright)foundondesktopsystems.

Thesearebigdifferencesthatyououghttotakeintoaccountinthe

designofyoursoftware.Otherwise,yoursoftwaremaydisappoint

yourusersandcausethemtoavoidusingyoursoftware.Tosatisfy

users,youmustlearnabouttheirexpectations,whichareoftenbased

ontheirexperiencesusingothersoftwarerunningonaparticular

smartdevice.

Onewaytounderstandyourusersistobecomeauserofthesmart

deviceyouaretargeting.[2]Forexample,ifyouplantowritesoftware

foraPocketPC,yououghttoacquireaPocketPCanduseitona

regularbasis.IfyouplantowritesoftwareforaSmartphone,itisnot

enoughthatyouhaveexperiencewithothermobilephones.Youmust

spendtimeusingthisparticularbreedofmobilephonetounderstand

whatusersexpecttofindintheuserinterfaceandhowtheyexpect

tonavigateit.

[2]AtMicrosoft,usingyourownproductsisreferredtoas"eatingyourowndogfood"(orsometimesjust

"dogfooding").Itisbasedontheidea—asexpressedbyMicrosoftCEOSteveBallmer—thatthequalityofdog

foodcompanies'productswouldnaturallyandinevitablyimproveiftheemployeesofthosecompanies

consumedtheirownproducts.AllMicrosoftemployeesareencouragedtoeattheirowndogfood,thatis,to

makeextensiveuseoftheirownproducts.



Nothingcanreplacetheexperienceofgettingfullyimmersedinthe

rhythmandbluesofauserinterfaceparadigm.Justasyoucannot

trulyexperiencemusicwithoutlisteningtoit,youcannottruly

understandauserinterfacewithoutspendingalotoftimetryingto

accomplishmanydifferentreal-worldtaskswhileusingthatinterface.

Youwilllikelyfeelfrustratedatfirstasyoutrytoaccomplishtasks



thatyoudoeasilyinotherenvironments,suchasfindingthesystem

tasklist,settingthetime,orviewingthecontentsofadirectoryin

thefilesystem.

Youareequallylikelytoenjoydiscoveringthoseuserinterface

elementsthatdomorethanjustovercometheapparentlimitationsof

asmartdeviceandthatinsteadhighlighttheavailablefeaturesofa

smartdevice.AsimpleexampleofthiscanbefoundintheSolitaire

programasimplementedontheSmartphone(seeFigure6.1).Ona

desktopPCandonaPocketPC,Solitaireisplayedbydraggingand

droppingcardsbyusingthemouse[3]orstylus.TheSmartphonehas

noexplicitpointingdevice;thenumerickeypadinsteadprovidesthe

meansforselectingcardlocations.Ashighlightedbythisexample,

cleveruseofnumerickeysisoftencentraltothedesignoftheinput

toaSmartphoneprogram.

[3]Onthedesktop,itispossible—butpainful—toplaySolitairebyusingthekeyboard.Thisillustratesanold

butnowdisregardedprincipleofWindowsuserinterfacedesignthatrecommendsthatmouseandkeyboard

inputbeequallysupportedforallinputoperations.Thisisbutoneelementthatseparatesgoodsoftwareon

desktopPCsfromgreatsoftware.Newersoftwaretakesamoremouse-centricapproach,workableuntila

mousebecomesunavailableordisabled.



Figure6.1.SolitaireontheSmartphone



Togiveyouasenseofwhatwearetalkingabout,herearesome

differencesyoumaynoticewhenyoustartusingaPocketPC.Thisis

meantnotasanexhaustivelistbutratherasastartingpointto

encourageyoutospendthetimegettingtoknowwhateversmart

deviceyouaretargetingwithyoursoftware.

APocketPChasasmall(240x320)screen(resolutionisonequartertheminimumVGA,640x480,rotatedby90degrees),

fullVGA,andalsolandscapeorientationonnewdevices.

Thescreeniscoveredbyatouch-sensitivepanel.

CharacterinputisaccomplishedbyusingtheSIP.

TheSIPsupportsbothhandwritingrecognitionandanon-screen

keyboard,twoofseveralinputmethods.Youcanwriteyourown

inputmethodwindow(atopicbeyondthescopeofthisbook).

PocketPCapplicationsrunfull-screen.

Whenyou"close"mostapplications,theyminimize(runinthe

background)insteadofshuttingdown.

ThePocketPCdoesnotcompletelyshutdownwhenyouturnthe

poweroff.Instead,thepowerswitchtogglesthePocketPC

betweenafullyonmodeandasuspendedmode.Whenasmart

deviceissuspended,allapplicationsinmemorystayinmemory

butareasleep.ThisallowsaPocketPC—andmanyother

WindowsCEdevices—tosupport"instant-on."

SomePocketPCapplicationsmakeextensiveuseofcontextor

pop-upmenus,whichappearwhenyoutapandholdthestyluson

ahotspot.Examplesofcontextmenusappearinthese

applications:Calendar,ContactList,andPocketExcel.



Event-DrivenInput



AllGUIsystemsprovideuserinputasevents[4]becauseevent-driven

inputworkswellforthetypeofinteractive,user-drivenapproachthat

GUIsystemsarebuilttoprovide.Theevent-drivenparadigm

predatesGUIsystems;interactivesimulatorsandcomputergames

requiresuchanapproach.Theseexceptionsaside,beforeGUI

systemswereintroducedmostcomputersoftwarewaswrittento

supportbatch-modeinput(somereadersmayrememberpunch

cards),screen-orientedformsdataentry,andline-orientedinput.

WiththeintroductionofGUIsystemsintheearly1980s,theeventdrivenparadigmenteredthemainstreamofcomputerprogramming.

[4]ThisstatementholdstrueforallGUIsystems,fromthefirstAppleMacintoshtothevariousmembersof

theMicrosoftWindowsoperatingsystem,allUNIXandLinux-basedGUIs,andboththe.NETFrameworkand

the.NETCompactFramework.Theymighthaveadifferentname—Win32usesthetermmessage—andthe

syntaxforretrievingandhandlingtheeventsmaydiffer,butthegeneraloperationofallGUIsystemsis

essentiallythesame.



Inputeventsstartlifeaselectricalsignalsdetectedbyhardwareand

transferredbyadevicedriverintotheoperatingsystem.The

operatingsystemstoresthisinputinaFIFO[5]queue,whicha

programretrievesbyreadingtheeventqueue.Someprogramming

interfacesexposetheeventretrievalmechanism,whileother

interfaceshideit.TheWin32APIexposesaninputloop—sometimes

calledthemessageloopormessagepump—whichprovidestheevent

source.[6]Bycontrast,themessagepumpishiddeninMFCprograms

andVisualBasic6programs.

[5]FIFOstandsfor"firstin,firstout."

[6]Win32programmerswillrecognizethe



GetMessagefunctionasthekeyfunctioninthatloop.



The.NETCompactFrameworkhasabuilt-in,hiddenmessagepump

thatliesburiedintheApplication[7]class.WhentheVisualStudio

.NETNewProjectWizardcreatesaC#program,thestaticRun

methodiscalledinwizard-providedcodelikethefollowing.

[7]Fullyqualifiedname:



System.Windows.Forms.Application.



///

///Themainentrypointfortheapplication.

///


staticvoidMain()

{

Application.Run(newForm1());

}



Anotherstaticmethodintheapplicationclass,DoEvents,pollsthe

queueforeventsanddeliversthemtotheirrespectivetargets.That

methodisequivalenttoastandardmessagepump,whichgetscalled

tohelpflushmessagesfromthemessagequeue.Aswediscussin

Chapter15,somemultithreadedprogramsneedtousethisfunction

toallowinterthreadaccesstocontrols(courtesyofthe

Control.Invokemethod.)

Whenanevententerstheoperatingsystemqueue,itsjourneyisonly

halfover.Fromthequeue,theeventmustfinditswaytothecorrect

window—aformorcontrolintheterminologyofthe.NETCompact

Framework—amongthemanywindowsinthesystem.Eachwindowis

ownedbyathread,andthatthreadhasamessagepumpresponsible

forretrievingtheinputforitswindows.Eachthreadisownedbyan

operatingsystemprocess.Thesecondhalfofthejourneygets

complicated,inshort,becausetheoperatingsystemsupports

multipleprocesses,multiplethreads,andmultiplewindows.Allthe

windowssitlikebabybirdsinanest,openingandclosingtheir

mouths,waitingforamouthfulfromtheirmother.Thechoiceofwho

getsfedisnotarbitrarybutdependsonaveryspecificsetof

conditions.

Inorderfora.NETCompactFrameworkwindow—meaningaformor

control—togetmouseorkeyboardinput,thefollowingconditionsare

necessary(assumingthattheassociatedclasssupportsagiven

event).



Thewindowmustbetheforegroundwindow(orachildofthe

foregroundwindow).

Thewindowmustbeenabled(Enabledpropertyistrue).

Thewindowmustbevisible(Visiblepropertyistrue).

Forkeyboardinput,thewindowmusthavethefocus(callthe

Focusmethodtosetfocustoawindow).

Formouseinput,thewindowmustliedirectlyunderthecursoror

underthestylus(onsystemswithoutacursor).

Afewwordsoneachitemareinorder.

TheForegroundWindow



Theforegroundwindowisthetop-levelwindowtheuserhaschosen

toworkwith.By"top-level"wemeanawindowwithoutaparent.In

general,eachprogramhasonetop-levelwindow.Youshouldallow

theusertoselectwhichtop-levelwindowtoworkwith.Thisideaisso

importantthatthe.NETCompactFrameworkdoesnotprovideaway

toforceawindowtotheforeground.ButtheWin32APIdoes—the

SetForegroundWindowfunction.Youneedthisfunctionwhenyou

havemultipleformsinaprogramandyouwanttocontrolwhichform

isvisibletotheuser.HereistheP/Invokedeclarationforcallingthis

Win32function:



[DllImport("coredll.dll",CharSet=CharSet.Unicode)]

publicstaticexternintSetForegroundWindow(IntPtrhWnd);



TheSetForegroundWindowfunctiontakesoneparameter,awindow

handle.Inthedesktop.NETFramework,thathandleisprovidedasa

property(Handle)ofacontrolorform.The.NETCompactFramework



doesnotprovidethisproperty,sowetakeanotherapproachtoget

thatvalue.WesetthefocusinmanagedcodeandthencalltheWin32

GetFocusfunctiontoquerythefocuswindow;thereturnvalueisa

windowhandle.Thefollowingcodefragmentshowsthedeclarations

andfunctioncallsneededtosetaformastheforegroundwindow.



usingSystem.Runtime.InteropServices;

//...

[DllImport("coredll.dll")]

publicstaticexternIntPtrGetFocus();

[DllImport("coredll.dll",CharSet=CharSet.Unicode)]

publicstaticexternintSetForegroundWindow(IntPtrhWnd);

privatevoidtimer1_Tick(objectsender,System.EventArgse)

{

this.TopLevelControl.Focus();

IntPtrhwnd=GetFocus();

SetForegroundWindow(hwnd);

}



EnabledversusDisabled



Togetmouseorkeyboardinput,acontrolmustbeenabled,meaning

thatitsEnabledpropertymustbetrue.Allcontrolssupportthis

property,evencontrolsthatdonotdirectlysupportmouseor

keyboardevents.Thispropertyinfluencesthreeaspectsofacontrol:

mouseinput,keyboardinput,andcontrolappearance.

Assumingthatacontrolsupportstheevents,theEnabledproperty

actslikeaswitch.Whenenabled,acontrolcangetmouseand

keyboardevents.Adisabledcontrolgetsnoinputevents.



Adisabledcontrolappearsgrayed,tonotifytheuserthatthecontrol

isnotavailable.Figure6.2comparestheappearanceofvarious

controlswhenenabledanddisabled.



Figure6.2.Enabledcontrols(black)comparedwith

disabledcontrols(grayedout)



Visibility



Togetmouseorkeyboardinput,acontrolmustbevisible—the

Visiblepropertymustbetrue.Likemanyprogrammingterms,the

meaningofvisibilitydoesnotmapexactlytoeverydayusage.A

controlmightnotbevisibletotheuser,butiftheVisiblepropertyis

true,thecontrolhasapresencewithintheuserinterfaceandsois

abletogetmouseorkeyboardinput.Whenthispropertyisfalse

however,noamountofcoaxingcancausethesystemtodelivereither

kindofinputtoacontrol.



KeyboardInput



Keyboardinputarrivesatthewindowthathasthefocus.The.NET

CompactFrameworksupportsaverysmallsetofPMEsrelatedto

focus.TheFocusedpropertyisaBooleanthatletsyoutestwhethera

specificcontrolhasthefocusornot.TheFocusmethodletsyou

assignthefocustoaspecificcontrol,whichcausesthefocustobe

takenawayfromwhatevercontrolpreviouslyhadthefocus.Thetwo

focus-relatedeventsareGotFocus,whichtellsacontrolthatitis

receivingthefocus,andLostFocus,whichtellsacontrolthatitis

losingthefocus.Thetwodatavalidationevents—Validatingand

Validated—aresentwheneveracontrollosesthefocus.

Forcontrolsthatcanreceivekeyboardinput,acontrolwiththefocus

getskeyboardinputasacombinationofthreeevents:KeyDown,

KeyPress,andKeyUp.TheKeyDownandKeyUpeventscorrespondto

theuserpushingandreleasingakeyboardkey(oritsequivalent,a

SIPkey).Thesetwoeventsareusefulfordetectingkeysthatdonot

produceanyprintedoutput—suchastheinputfromthearrowkeys

(left,up,right,anddown),alsogeneratedwhentheuserclicksthe

directionpadonaPocketPC.(ManyPocketPCshavearockerswitch,

whichistreatedasuparrowanddownarrowinput.)

TheKeyPresseventdeliversalphanumerickeyboardinput

information,thecharacterinputinformationnormallyassociatedwith

printablecharacters.Inafewcases,KeyPresseventsaregenerated

fornonprintablekeysincludingtheenter,tab,andbackspacekeys.

Togetasenseoftherelationshipbetweenuserinputandthe

associatedevents,wewrotetheFormEventsprogram(introducedin

Chapter5).Figure6.3showstheeventsgeneratedbytypingthe

letter"a".Thisprogramshowseventsastheyarereceivedbythe

program'sform,andforthatreasonwesetthefocustotheform—by

clickingtheFormFocusbutton—priortotypingtheletter"a"onthe

SIPkeyboard.ThatiswhythefirsteventshownistheGotFocus

event.Theeventsdirectlyassociatedwithtyping"a"arethe

following.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 6.  Mouse and Keyboard Input

Tải bản đầy đủ ngay(0 tr)

×