Tải bản đầy đủ - 0 (trang)
Hack 57. Build a Time-Out Feature

Hack 57. Build a Time-Out Feature

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

canbeavoided.Aproductivemeasureforthissituationisto

closeaforminwhichnoactivityissensedafteraperiodof

time.Inotherwords,ifthefirstuserhasnotcompletedany

changestotherecordwithinaspecifiedtime,theformshould

justclose.Closingtheformendstherecord-editingprocess,

andthechangesaresavedautomatically.Thealternative,to

dropthechanges,isdiscussedattheendofthishack.



6.4.1.It'sAboutTime

FormshaveanintrinsictimercontrolandTimerevent.Ifyou're

familiarwithVisualBasic,youknowhowtoactuallyplacea

timercontrolonaform.InAccess,thecontroliseffectively

alreadyontheform,althoughyoudon'tseeit.Instead,youuse

thepropertysheettosettheIntervalpropertyandtoindicate

whatoccursintheOnTimerevent.

Todisplaythepropertysheet,opentheforminDesignmode,

andpressF4onthekeyboard.Ifnecessary,makesurethe

propertysheetisdisplayingpropertiesabouttheformitself,not

aboutoneofthecontrolsorsections.SelectFormfromthe

drop-downboxatthetopofthepropertysheet.

Figure6-5showsthepropertysheetsettodisplaythe

propertiesfortheform.TheOnTimerandTimerIntervalproperties

arefoundonboththeEventtabandtheAlltab.



Youcandisplaythepropertysheetinafewways.YoucanpressF4,or

youcanpressAlt-Enter.YoucanalsousetheView

Properties

menu,orjustclickthePropertiesbuttonontheFormDesigntoolbar.



TheIntervalpropertyacceptsvaluesbetween0and2,147,483,647



milliseconds.Asettingof1000equalsonesecond.The10000

settingshowninFigure6-5istheequivalentof10seconds.By

theway,thelargestsettingof2,147,483,647equalsalmost25

days.Yes,youcanscheduleanAccesseventevery25days!

TheOnTimereventpropertylinkstoeitheramacrooracode

procedure.Inthisexample,acodeprocedurewaswritten.I'll

explainthecodesoon,butfirst,let'sexaminetheform'sdesign.



6.4.2.InGoodForm

Figure6-6illustratestheformdesign,fieldlist,andproperty

sheet.Noticethetextboxcontrolintheformheaderthatisn't

boundtoafield.Thepropertysheetissettodisplaythe

propertiesoftheunboundbox,txtTime,anditsVisibleproperty

issettoNo.Inotherwords,whentheformisinViewmode,the

txtTimetextboxwon'tbeseen.



Figure6-5.SettingtheTimerIntervalandOn

Timerevent



Figure6-6.Anunboundtextboxtoholdatime

reference



ThetxtTimetextboxisn'tmeanttobeusedforentry.Instead,

itholdsasnapshotofthecomputer'sclocktime,atthemoment

theformisactivated.Tomakethishappen,youneedtoentera

littlecodeintheform'sActivateevent.

Togettotheeventcodestub,select[EventProcedure]from

thedrop-downmenutotherightofOnActivateintheproperty

sheetandthenclicktheellipses(…)button,asshowninFigure

6-7.Thisbringsyoutotheform'scodemodule,rightatthe

startoftheActivateevent.How'sthatforconvenience?



Figure6-7.Gettingtoaneventcodestubfrom

thepropertysheet



HereisthecodetoenterintheActivateevent:



PrivateSubForm_Activate()

Me.txtTime=Now



EndSub



TheOnTimereventcontainstheDateDifffunction,settotestfor

thedifferenceinsecondsbetweentheestablishedform

activationtimeandthecurrenttime.Fromthepropertysheet,

select[EventProcedure]inthedrop-downmenutotherightof

OnTimer.Clicktheellipsesbuttonandenterthiscode:











PrivateSubForm_Timer()

IfDateDiff("s",Me.txtTime,Now)>5Then

DoCmd.Close

EndIf







EndSub



ThefirstparameteroftheDateDifffunctionindicateswhich

intervaltotest;inthiscase,sisforseconds.Thefunctiontests

ifmorethanfivesecondshavelapsedbetweenthetimestored

inthetxtTimetextboxandnow.Bearinmindthatthereare

twovaluestocoordinatehere:thetimerintervalandhowmany

secondstotestfor.

Thisexampleissetuptotestevery10secondsifthereisa

differenceoffiveseconds,butyoucanchangethesenumbers.

Forexample,itmightbeeasierontheuserifthetimerinterval

is30seconds.Thereisabalanceofwhatmakessensehere.If

usersarelikelytoeditthesamerecordsoften,makethe

intervalshorter.



TheNow()functionreturnsthesystemtime.Everycomputerkeepsan

internalclockrunning.Whentimingevents,it'snecessarytostartwith

abaselinetime.TheNow()functiontakesasnapshotofthetime,which

isthencomparedtoalatertime(effectivelyanothersnapshot,butlater

intime).Subtractingthefirstsnapshotfromthesecondsnapshot

equalstheelapsedtime.Incidentally,thecomputerclockisalsousedin

programsthatallowyoutoenter"today'sdate."Sometimes,theclock

needstobereset.



Ifwestoppedhere,theformwouldclose10secondsafter

beingopened.Thatis,uponthefirstrunoftheOnTimerevent

(whichoccurs10secondsaftertheformisopened)adifference

greaterthanfivesecondsisfound,andtheDoCmd.Closelineruns,

closingtheform.Butourgoalistoclosetheformonlywhen

thereisnoactivity,notjustfortheheckofit.

Thekeytomakingthishackworkistoaddcodetoeachchange



eventforthevarioustextentryboxesontheform.Theformin

thisexamplehastextboxesforeditingemployeename,

department,title,andsoon.TheChangeeventforeachtextbox

receivesasinglelineofcodetoupdatethetxtTimetextbox

withthecurrenttime.Inotherwords,everytimeachangeis

madeinanentrytextboxthetxtTimetextbox(remember,this

oneisinvisible)isresettoNow,likethis:



PrivateSubDepartment_Change()

Me.txtTime=Now



EndSub



TheChangeeventfireseachtimeacharacterisenteredor

backspacedoutofthetextbox.Therefore,asausertypesin

oneoftheentrytextboxes,thetxtTimetextboxisconstantly

updatedwiththecurrenttime.Then,whenthetimerevent

fires,theDateDifffunctionreturnsadifferenceoflessthanfive

seconds,andtheformstaysopen.Onlywhentheformisleft

idledoesadifferencegreaterthanfivesecondsoccur,thereby

closingtheform.

Figure6-8showshowtheform'scodemoduleshouldlookafter

theseroutineshavebeenentered.It'sOKifyoureventroutines

aren'tinthesameorder.



Figure6-8.Thecodethathandlesaninactive

form



6.4.3.HackingtheHack

Youcanimplementthishackinmanydifferentways.Sofar,all

weknowishowtoresetthebaselinetimeeachtimea

characterisenteredwiththekeyboard.Also,theonlyaction

afteraperiodofinactivityhasbeentoclosetheform.Hereare

someotherideas.



6.4.3.1Resetthetimewhenthemouseismoved.



Inadditiontocapturingkeyboardentriesasawaytoresetthe

timeheldintheinvisibletextbox,itmakessensetodothis

wheneverthemouseismovedaswell.Somepeoplearequick

onthemouse,andjustgivingthemouseapushkeepstheform

open.Infact,Ioftendothistokeepmyscreensaverfrom

startingup.

AccessformscanalsousetheMouseMoveevent.Insertcodeinto

theMouseMoveeventinthesamemannerexplainedearlier.The

purposeofthecodeisthesame,toresettheinvisibletextbox

toNow.



PrivateSubTitle_MouseMove(ButtonAsInteger,_

ShiftAsInteger,XAsSingle,YAsSingle)

Me.txtTime=Now

EndSub



Aslongasthemouseismovedatleastonceevery10seconds,

theformwillstayopen.



6.4.3.2Lettheuserdecidethetimerinterval.

Eachuserhashisownwayofworking,nottomentionhisown

speedofworking.So,insteadofhardcodingthetimer'sinterval

value,whynotlettheuserdecidewhatisbest?Todothis,you

havetobuildawaytolethimselecttheintervalintotheform

(orsomewhereelse,suchasinapreferencesarea).Figure6-9

showshowtheformhasbeenmodifiedbyaddingacombobox.

Thecomboboxletstheuserselectfromalistofpossible

values.



Figure6-9.Lettingtheuserdecidehowlongto

waitbeforeclosingtheform



Thecodeisupdatedaswell.Thecomboboxhasbeennamed

cmbSeconds.ItsRowSourceTypeissettoValueList,andtheRow

Sourceissettothechoices10,20,30,40,50,and60.Whenthe

userselectsavaluefromthecombobox,thecombobox'sChange

eventfirestoupdatetheinvisibletextboxtothecurrenttime.

Also,theform'sActivateeventnowtakescareofestablishinga

defaulttimetowait20secondsinthiscase,asshowninFigure

6-10.

It'snecessarytohaveadefaultvaluetouseuntilorunlessthe

userselectsaninterval.Finally,thenumberofelapsedseconds

thataretestedforisnowalwaysonefewerthantheinterval

selectedinthecombobox.Figure6-10showstheupdatedcode

module.



Figure6-10.SettingtheIntervalpropertywith

thecomboboxChangeevent



6.4.3.3Savetherecordbutleavetheformopen.

Justbecausearecordisdisplayedinaformdoesn'tnecessarily

meanitisbeingedited.TheDirtypropertyistrueifeditshave

beenmadeorfalseifnodatahaschanged.Youcanchangethe

codeintheform'sTimereventtotesttheDirtyproperty.Ifitis

true,therecordissaved,andamessageispresented,as

showninFigure6-11.IfDirtyisfalse,andnoeditisoccurring,

nothinghappens.Eitherwaytheformstaysopen.

ThenewcodefortheTimereventusesapairofnestedIf

statements.First,iftheelapsedtimeisgreaterthanthe



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

Hack 57. Build a Time-Out Feature

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

×