为我的所有表单设置相同的图标有没有一种方法可以为我的所有表单设置相同的图标,而不必一一更改?类似于为解决方案中的所有项目设置GlobalAssemblyInfo。一个选项来自在构造函数中设置Icon的通用基础Forminheritance(可能来自resx)。另一个选择可能是PostSharp-似乎应该可以通过AOP执行此操作(设置.Icon);但不是微不足道的。最后,您可以使用一个简单的实用方法(可能是一个扩展方法)来做同样的事情。最重要的是,使用第一个选项,您可能会冒着从Ctrl+H(全部替换):Form或:System.Windows.Forms.Form到:MyCustomForm的风险。在ProjectProperties>Application>IconsandManifests>浏览*.ico文件并将它们添加到那里。在Form的构造函数或_Load事件中,只需添加:this.Icon=Icon.ExtractAssociatedIcon(Application.ExecutablePath);除了Marc的建议之外,您可能希望您的表单自动继承/调用它们的执行程序集图标。这可以通过将以下代码添加到继承的表单来完成:publicMyCustomForm(){Icon=GetExecutableIcon();}publicIconGetExecutableIcon(){IntPtr大;IntPtr小;ExtractIconEx(Application.ExecutablePath,0,outlarge,outsmall,1);返回Icon.FromHandle(小);}[DllImport("Shell32")]publicstaticexternintExtractIconEx(stringsFile,intiIndex,outIntPtrpiLargeVersion,outIntPtrpiSmallVersion,intamountIcons);我不确定我是否想在这里使用继承,所以我使用了扩展方法:然后在任何形式的构造函数中:this.SetAppIcon();注意:如果您尝试从网络位置运行该应用程序,将导致崩溃在构造函数中设置它的另一种方法是覆盖Owner属性,并获取所有者表单的图标。publicnewFormOwner{set{this.Icon=(value==null?null:value.Icon);base.Owner=值;}得到{返回base.Owner;}}这个是把所有的form都设置成同一个icon不用一个个改方法。这是我在我的应用程序中编写的代码。FormUtils.SetDefaultIcon();这是一个可以使用的完整示例。staticclassProgram{//////应用程序的主要入口点。///[STAThread]staticvoidMain(string[]args){Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);//这里是。FormUtils.SetDefaultIcon();应用程序运行(新表格());这是FormUtils类:使用System.Drawing;publicstaticclassFormUtils{publicstaticvoidSetDefaultIcon(){varicon=Icon.ExtractAssociatedIcon(EntryAssemblyInfo.ExecutablePath);typeof(Form).GetField("defaultIcon",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Static).SetValue(null,icon);这是EntryAssemblyInfo类。对于此示例,这将被截断。这是我从System.Winforms.Application中获取的自定义编码类。使用系统安全;使用System.Security.Permissions;使用System.Reflection;使用系统诊断;publicstaticclassEntryAssemblyInfo{privatestaticstring_executablePath;publicstaticstringExecutablePath{get{if(_executablePath==null){PermissionSetpermissionSets=newPermissionSet(PermissionState.None);permissionSets.AddPermission(newFileIOPermission(PermissionState.Unrestricted));permissionSets.AddPermission(newSecurityPermission(SecurityPermissionFlag.UnmanagedCode));permissionSets.Assert();字符串uriString=null;varentryAssembly=Assembly.GetEntryAssembly();如果(entryAssembly==null)uriString=Process.GetCurrentProcess().MainModule.FileName;elseuriString=entryAssembly.CodeBase;PermissionSet.RevertAssert();if(string.IsNullOrWhiteSpace(uriString))thrownewException("CannotGetEntryAssemblyorProcessMainModuleFileName");else{varuri=newUri(uriString);如果(uri.IsFile)_executablePath=string.Concat(uri.LocalPath,Uri.UnescapeDataString(uri.Fragment));否则_executablePath=uri.ToString();}}返回_executablePath;我不确定MSVSdesigner是否可以直接从FormDerivedforms处理如果不能,那么你可以尝试将主窗体的图标复制到所有其他窗体:form.icon=MainFrom.IconforeachformintheFormscollectionormaybeineachForm's_Loadedevent:以上是C#学习教程:为我所有的表单设置相同的图标来共享所有的内容。如果对大家有用,需要详细了解C#学习教程,希望大家多多关注—icon=MainFrom.Icon本文来自网络收藏不代表立场,如涉及侵权,请点击右边联系管理员删除。如需转载请注明出处:
