![毕业设计翻译文稿-Create-a-Windows-Based-Application-from-the-Command-Line_第1页](http://file4.renrendoc.com/view/b10a556e4682255b6ccffc4cd5b6549c/b10a556e4682255b6ccffc4cd5b6549c1.gif)
![毕业设计翻译文稿-Create-a-Windows-Based-Application-from-the-Command-Line_第2页](http://file4.renrendoc.com/view/b10a556e4682255b6ccffc4cd5b6549c/b10a556e4682255b6ccffc4cd5b6549c2.gif)
![毕业设计翻译文稿-Create-a-Windows-Based-Application-from-the-Command-Line_第3页](http://file4.renrendoc.com/view/b10a556e4682255b6ccffc4cd5b6549c/b10a556e4682255b6ccffc4cd5b6549c3.gif)
![毕业设计翻译文稿-Create-a-Windows-Based-Application-from-the-Command-Line_第4页](http://file4.renrendoc.com/view/b10a556e4682255b6ccffc4cd5b6549c/b10a556e4682255b6ccffc4cd5b6549c4.gif)
![毕业设计翻译文稿-Create-a-Windows-Based-Application-from-the-Command-Line_第5页](http://file4.renrendoc.com/view/b10a556e4682255b6ccffc4cd5b6549c/b10a556e4682255b6ccffc4cd5b6549c5.gif)
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
CreateaWindows-BasedApplicationfromtheCommandLine(题目)ProblemYouneedtousetheC#command-linecompilertobuildanapplicationthatprovidesaWindowsForms–basedGUI.SolutionCreateaclassthatextendstheSystem.Windows.Forms.Formclass.(Thiswillbeyourapplication’smainform.)Inoneofyourclasses,ensureyouimplementastaticmethodnamedMain.IntheMainmethod,createaninstanceofyourmainformclassandpassittothestaticmethodRunoftheSystem.Windows.Forms.Applicationclass.Buildyourapplicationusingthecommand-lineC#compiler,andspecifythe/target:winexecompilerswitch.■NoteIfyouownVisualStudio,youwillmostoftenusetheWindowsApplicationprojecttemplatetocreatenewWindowsForms–basedapplications.BuildinglargeGUI-basedapplicationsisatime-consumingundertakingthatinvolvesthecorrectinstantiation,configuration,andwiringupofmanyformsandcontrols.VisualStudioautomatesmuchoftheworkassociatedwithbuildinggraphicalapplications.TryingtobuildalargegraphicalapplicationwithouttheaidoftoolssuchasVisualStudiowilltakeyoumuchlonger,beextremelytedious,andresultinagreaterchanceofbugsinyourcode.However,itisalsousefultoknowtheessentialsrequiredtocreateaWindows-basedapplicationusingthecommandlineincaseyouareeverworkingonamachinewithoutVisualStudioandwanttocreateaquickutilitytoautomatesometaskorgetinputfromauser.HowItWorksBuildinganapplicationthatprovidesasimpleWindowsGUIisaworldawayfromdevelopingafull-fledgedWindows-basedapplication.However,youmustperformcertaintasksregardlessofwhetheryouarewritingtheWindowsequivalentofHelloWorldorthenextversionofMicrosoftWord,includingthefollowing:•Foreachformyouneedinyourapplication,createaclassthatextendstheSystem.Windows.Forms.Formclass.•Ineachofyourformclasses,declaremembersthatrepresentthecontrolsthatwillbeonthatform,suchasbuttons,labels,lists,andtextboxes.Thesemembersshouldbedeclaredprivateoratleastprotectedsothatotherprogramelementscannotaccessthemdirectly.Ifyouneedtoexposethemethodsorpropertiesofthesecontrols,implementthenecessarymembersinyourformclass,providingindirectandcontrolledaccesstothecontainedcontrols.•Declaremethodsinyourformclassthatwillhandleeventsraisedbythecontrolscontainedbytheform,suchasbuttonclicksorkeypresseswhenatextboxistheactivecontrol.Thesemethodsshouldbeprivateorprotectedandfollowthestandard.NETeventpattern(describedinrecipe13-11).It’sinthesemethods(ormethodscalledbythesemethods)whereyouwilldefinethebulkofyourapplication’sfunctionality.•Declareaconstructorforyourformclassthatinstantiateseachoftheform’scontrolsandconfigurestheirinitialstate(size,color,position,content,andsoon).Theconstructorshouldalsowireuptheappropriateeventhandlermethodsofyourclasstotheeventsofeachcontrol.•DeclareastaticmethodnamedMain—usuallyasamemberofyourapplication’smainformclass.Thismethodistheentrypointforyourapplication,anditcanhavethesamesignaturesasthosementionedinrecipe1-1.IntheMainmethod,callApplication.EnableVisualStylestoallowXPthemesupport,createaninstanceofyourapplication’smainform,andpassitasanargumenttothestaticApplication.Runmethod.TheRunmethodmakesyourmainformvisibleandstartsastandardWindowsmessagelooponthecurrentthread,whichpassestheuserinput(keypresses,mouseclicks,andsoon)toyourapplicationformasevents.ConnecttoaDatabaseProblemYouneedtoopenaconnectiontoadatabase.SolutionCreateaconnectionobjectappropriatetothetypeofdatabasetowhichyouneedtoconnect.AllconnectionobjectsimplementtheSystem.Data.IDbConnectioninterface.ConfiguretheconnectionobjectbysettingitsConnectionStringproperty.Opentheconnectionbycallingtheconnectionobject’sOpenmethod.HowItWorksThefirststepindatabaseaccessistoopenaconnectiontothedatabase.TheIDbConnectioninterfacerepresentsadatabaseconnection,andeachdataproviderincludesauniqueimplementation.HereisthelistofIDbConnectionimplementationsforthefivestandarddataproviders:•System.Data.Odbc.OdbcConnection•System.Data.OleDb.OleDbConnection•System.Data.OracleClient.OracleConnection•System.Data.SqlServerCe.SqlCeConnection•System.Data.SqlClient.SqlConnectionYouconfigureaconnectionobjectusingaconnectionstring.Aconnectionstringisasetofsemicolon-separatedname-valuepairs.Youcansupplyaconnectionstringeitherasaconstructorargumentorbysettingaconnectionobject’sConnectionStringpropertybeforeopeningtheconnection.Eachconnectionclassimplementationrequiresthatyouprovidedifferentinformationintheconnectionstring.RefertotheConnectionStringpropertydocumentationforeachimplementationtoseethevaluesyoucanspecify.Possiblesettingsincludethefollowing:•Thenameofthetargetdatabaseserver•Thenameofthedatabasetoopeninitially•Connectiontime-outvalues•Connection-poolingbehavior(seerecipe9-2)•Authenticationmechanismstousewhenconnectingtosecureddatabases,includingprovisionofausernameandpasswordifneeded.Onceconfigured,calltheconnectionobject’sOpenmethodtoopentheconnectiontothedatabase.Youcanthenusetheconnectionobjecttoexecutecommandsagainstthedatasource(discussedinrecipe9-3).Thepropertiesofaconnectionobjectalsoallowyoutoretrieveinformationaboutthestateofaconnectionandthesettingsusedtoopentheconnection.Whenyou’refinishedwithaconnection,youshouldalwayscallitsClosemethodtofreetheunderlyingdatabaseconnectionandsystemresources.IDbConnectionextendsSystem.IDisposable,meaningthateachconnectionclassimplementstheDisposemethod.DisposeautomaticallycallsClose,makingtheusingstatementaverycleanandefficientwayofusingconnectionobjectsinyourcode.Youachieveoptimumscalabilitybyopeningyourdatabaseconnectionaslateaspossibleandclosingitassoonasyouhavefinished.Thisensuresthatyoudonottieupdatabaseconnectionsforlongperiods,soyougiveallcodethemaximumopportunitytoobtainaconnection.Thisisespeciallyimportantifyouareusingconnectionpooling.PerformAsynchronousDatabaseOperationsAgainstSQLServerProblemYouneedtoexecuteaqueryorcommandagainstaSQLServerdatabaseasabackgroundtaskwhileyourapplicationcontinueswithotherprocessing.SolutionUsetheBeginExecuteNonQuery,BeginExecuteReader,orBeginExecuteXmlReadermethodoftheSystem.Data.SqlClient.SqlCommandclasstostartthedatabaseoperationasabackgroundtask.ThesemethodsallreturnaSystem.IAsyncResultobjectthatyoucanusetodeterminetheoperation’sstatusorusethreadsynchronizationtowaitforcompletion.UsetheIAsyncResultobjectandthecorrespondingEndExecuteNonQuery,EndExecuteReader,orEndExecuteXmlReadermethodtoobtaintheresultoftheoperation.■NoteOnlytheSqlCommandclasssupportstheasynchronousoperationsdescribedinthisrecipe.TheequivalentcommandclassesfortheOracle,SQLServerCE,ODBC,andOLEDBdataprovidersdonotprovidethisfunctionality.HowItWorksYouwillusuallyexecuteoperationsagainstdatabasessynchronously,meaningthatthecallingcodeblocksuntiltheoperationiscomplete.Synchronouscallsaremostcommonbecauseyourcodewillusuallyrequiretheresultoftheoperationbeforeitcancontinue.However,sometimesit’susefultoexecuteadatabaseoperationasynchronously,meaningthatyoustartthemethodinaseparatethreadandthencontinuewithotheroperations.■NoteToexecuteasynchronousoperationsoveraSystem.Data.SqlClient.SqlConnectionconnection,youmustspecifythevalueAsynchronousProcessing=trueinitsconnectionstring.Asof.NETFramework2.0,theSqlCommandclassimplementstheasynchronousexecutionpatternsimilartothatdiscussedinrecipe4-2.Aswiththegeneralasynchronousexecutionpatterndescribedinrecipe4-2,theargumentsoftheasynchronousexecutionmethods(BeginExecuteNonQuery,BeginExecuteReader,andBeginExecuteXmlReader)arethesameasthoseofthesynchronousvariants(ExecuteNonQuery,ExecuteReader,andExecuteXmlReader),buttheytakethefollowingtwoadditionalargumentstosupportasynchronouscompletion:•ASystem.AsyncCallbackdelegateinstancethatreferencesamethodthattheruntimewillcallwhentheasynchronousoperationcompletes.Themethodisexecutedinthecontextofathread-poolthread.Passingnullmeansthatnomethodiscalledandyoumustuseanothercompletionmechanism(discussedlaterinthisrecipe)todeterminewhentheasynchronousoperationiscomplete.•Anobjectreferencethattheruntimeassociateswiththeasynchronousoperation.Theasynchronousoperationdoesnotusenorhaveaccesstothisobject,butit’savailabletoyourcodewhentheoperationcompletes,allowingyoutoassociateusefulstateinformationwithanasynchronousoperation.Forexample,thisobjectallowsyoutomapresultsagainstinitiatedoperationsinsituationswhereyouinitiatemanyasynchronousoperationsthatuseacommoncallbackmethodtoperformcompletion.TheEndExecuteNonQuery,EndExecuteReader,andEndExecuteXmlReadermethodsallowyoutoretrievethereturnvalueofanoperationthatwasexecutedasynchronously,butyoumustfirstdeterminewhenithasfinished.Herearethefourtechniquesfordeterminingifanasynchronousmethodhasfinished:•Blocking:Thismethodstopstheexecutionofthecurrentthreaduntiltheasynchronousoperationcompletesexecution.Ineffect,thisismuchthesameassynchronousexecution.However,youdohavetheflexibilitytodecideexactlywhenyourcodeenterstheblockedstate,givingyoutheopportunitytocarryoutsomeadditionalprocessingbeforeblocking.•Polling:Thismethodinvolvesrepeatedlytestingthestateofanasynchronousoperationtodetermineifit’scomplete.Thisisaverysimpletechniqueandisnotparticularlyefficientfromaprocessingperspective.Youshouldavoidtightloopsthatconsumeprocessortime.It’sbesttoputthepollingthreadtosleepforaperiodusingThread.Sleepbetweencompletiontests.Becausepollinginvolvesmaintainingaloop,theactionsofthewaitingthreadarelimited,butyoucaneasilyupdatesomekindofprogressindicator.•Waiting:ThismethodusesanobjectderivedfromtheSystem.Threading.WaitHandleclasstosignalwhentheasynchronousmethodcompletes.Waitingisamoreefficientversionofpollingandinadditionallowsyoutowaitformultipleasynchronousoperationstocomplete.Youcanalsospecifytime-outvaluestoallowyourwaitingthreadtofailiftheasynchronousoperationtakestoolong,orifyouwanttoperiodicallyupdateastatusindicator.•Callback:Thisamethodthattheruntimecallswhenanasynchronousoperationcompletes.Thecallingcodedoesnotneedtotakeanystepstodeterminewhentheasynchronousoperationiscompleteandisfreetocontinuewithotherprocessing.Callbacksprovidethegreatestflexibility,butalsointroducethegreatestcomplexity,especiallyifyouhavemanyconcurrentlyactiveasynchronousoperationsthatallusethesamecallback.Insuchcases,youmustuseappropriatestateobjectstomatchcompletedmethodsagainstthoseyouinitiated.■CautionWhenusingtheasynchronouscapabilitiesoftheSQLServerdataprovider,youmustensurethatyourcodedoesnotinadvertentlydisposeofobjectsthatarestillbeingusedbyotherthreads.PayparticularattentiontoSqlConnectionandSqlCommandobjects.
创建一个基于Windows的应用程序的命令行
问题您需要使用C#命令行编译器建立一个应用程序,提供了一个
Windows窗体为基础的图形用户界面。
解决方案创建一个类,它扩展了System.Windows.Forms.Form类。(这将是您的应用的主要形式。)在您的一个类,确保您执行一个静态方法命名为主要。在Main方法中,创建一个实例,您的主窗体类,并将其交给静态方法运行System.Windows.Forms.Application级。建立您的应用程序使用命令行C#编译器,并指定/目标:winexe编译开关。■注意:如果您自己的VisualStudio中,您将最经常使用的Windows应用程序项目模板创建新的Windows窗体应用程序。建设大型基于GUI应用是一个非常耗时的工作,涉及到正确的实例,配置和布线的许多形式和控制。大部分的VisualStudio的自动化有关的工作与建设的图形应用。试图建立一个大型的图形应用程序的帮助的工具如VisualStudio将带您更长时间,是极其单调乏味,并导致更多的机会的错误在您的代码。然而,它也是有用的知识的基本要求,以建立一个基于Windows的应用程序使用命令行的情况下,您是以往的工作机器上没有VisualStudio和希望创建一个自动化的快速实用的一些任务或者输入一个用户。如何运作建立一个应用程序,提供了一个简单的Windows图形用户界面是一个远离世界发展一个正式的基于Windows的应用程序。但是,您必须执行某些任务,无论您是否有书面的Windows相当于世界您好或下一版MicrosoftWord中,包括下列内容:•对于每一个表格您需要在您的应用程序,创建一个类,它扩展了System.Windows.Forms.Form类。•在您的每个班的形式,宣布各成员,代表了控制,将在这形式,如按钮,标签,列表和文本框。这些成员应被宣布为私营或者至少保护的,所以其他程序的内容不能访问他们直接联系。如果您需要揭露的方法或属性这些管制,实施必要的成员您的窗体类,提供间接和控制进入载管制。•宣告方法在您的窗体类的事件,将处理所提出的控制载的形式,如点击按钮或按键时,一个TextBox是主动控制。这些方法应该私人或受保护的,并按照标准。NET的活动模式(描述在食谱13-11)。这是在这些方法(或方法调用这些方法)如果您将界定的大部分应用程序的功能。•声明一个构造形式为您的每一个类实例的形式的控制和配置的初始状态(大小,颜色,位置,内容等)。构造应还电线了适当的事件处理方法,您的类的事件,每个控制。•声明一个静态方法命名主通常作为一名应用程序的主要形式一流的。此方法是切入点,为您的应用程序,它可以有相同的签名所提到的那些食谱1-1。在Main方法中,调用Application.EnableVisualStyles来让XP的主题支持下,创建一个实例应用程序的主要形式,并通过它作为论点静态Application.Run方法。run方法使您的主要形式可见并启动一个标准的Windows消息循环的当前线程,这会将使用者输入(按键,鼠标点击,等等)到您的申请表的事件。连接到数据库问题您需要打开一个连接到一个数据库。解决方案创建一个连接对象适当类型的数据库,你需要连接。所有连接对象执行System.Data.IDbConnection接口。配置通过设置Connection对象的ConnectionString属性。打开连接的要求Connection对象的Open方法。如何运作第一步,数据库访问是打开一个连接到数据库。该IDbConnection界面是一个数据库连接,每个数据类库提供一个独特的执行。这里是IDbConnection实施的五个标准数据类库:•System.Data.Odbc.OdbcConnection•System.Data.OleDb.OleDbConnection•System.Data.OracleClient.OracleConnection•System.Data.SqlServerCe.SqlCeConnection•System.Data.SqlClient.SqlConnection您配置一个连接对象使用一个连接字符串。一个连接字符串是一套分号分隔的名称和值的配对。您可以提供一个连接字符串作为一个构造函数参数或通过设置Connection对象的ConnectionString属性之前开放连接。每个连接级执行,您需要提供不同的信息连接字符串。参阅ConnectionString属性为每个文件执行看到价值,您可以指定。可能的设置包括以下内容:•名称的目标数据库服务器•资料库名称开放初期•连接超时值•连接池的行为•验证机制时所使用的数据库连接的担保,包括提供一个用户名和密码,如果需要的话。一旦配置,调用Connection对象的Open方法打开连接数据库。然后,您可以使用Connection对象来执行命令,对数据来源。的属性Connection对象也可让您检索信息的连接状态和设置用于打开连接。当您完成连接,你应该总是要求其关闭的方法免费的基本数据库连接和系统资源。IDbConnection延伸System.IDisposable,也就是说,每个连接类实现Dispose方法。处置自动呼吁关闭,使using语句一个非常廉洁和高效率的方法使用连接对象在您的代码。您达到最佳的可扩展性,开放的数据库连接才可能和关闭当您已经完成。这可以确保您不占用数据库连接很长时间,所以你让所有代码的最大机会获得连接。这一点尤其重要如果您使用的是连接池。执行异步数据库操作SQLServer问题您需要执行查询
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2024-2025学年高中政治课时分层作业9订立合同有学问含解析新人教版选修5
- 2024-2025学年高中数学课时分层作业4平面的基本性质含解析苏教版必修2
- 2024年高中政治第一单元生活与消费第1课第1框揭开货币的神秘面纱作业含解析新人教版必修1
- 2024年高考化学精准押题练第13题化学实验基础含解析
- 2024-2025学年高中物理第五章6向心力练习含解析新人教版必修2
- 检验工作人员年终总结
- 大学暑期社会实践个人总结
- 外科护士工作计划报告
- 鲁人版道德与法治七年级下册15.2《生命最宝贵》听课评课记录
- 东入合作协议书
- 护工(陪护)培训教材(完整版)资料
- absciex lc ms qtrapanalyst软件定量操作Analyst在如右图的弹出窗口
- 骨科的疼痛管理
- 前列腺癌诊断治疗指南
- 中国银行招聘笔试真题「英语」
- 江苏省2023年对口单招英语试卷及答案
- GB/T 35506-2017三氟乙酸乙酯(ETFA)
- GB/T 25784-20102,4,6-三硝基苯酚(苦味酸)
- 特种设备安全监察指令书填写规范(特种设备安全法)参考范本
- 硬笔书法全册教案共20课时
- 《长方形的面积》-完整版课件
评论
0/150
提交评论