【问题标题】:C# console application iconC# 控制台应用程序图标
【发布时间】:2009-07-23 08:18:29
【问题描述】:

有谁知道如何在代码中设置 C# 控制台应用程序的图标(不使用 Visual Studio 中的项目属性)?

【问题讨论】:

    标签: c# console-application imageicon


    【解决方案1】:

    您可以在项目属性中更改它。

    查看这篇 Stack Overflow 文章:Is it possible to change a console window's icon from .net?

    总结一下,在 Visual Studio 中右键单击您的项目(不是解决方案)并选择属性。在“应用程序”选项卡的底部有一个“图标和清单”部分,您可以在其中更改图标。

    【讨论】:

    • 我们是否要忽略 OP 明确表示他们想要一种在代码中实现它的方法......而不是从项目属性中??
    • 这提供了我正在寻找的解决方案。也许不是 OP 所要求的
    【解决方案2】:

    您不能在代码中指定可执行文件的图标 - 它是二进制文件本身的一部分。

    如果有帮助,您可以从命令行使用/win32icon:<file>,但您不能在应用程序的代码中指定它。不要忘记,在显示应用程序图标的大多数情况下,您的应用程序根本没有运行!

    假设您指的是资源管理器中文件本身的图标。如果您指的是应用程序的图标它正在运行时,如果您只是双击文件,我相信它永远只是控制台本身的图标。

    【讨论】:

    • 我不确定这是否对我有用。我正在使用 CSharpCodeProvider 在 C# 应用程序中编译一个 concole 应用程序,我真的非常想为生成的二进制文件设置资源管理器图标...
    • 我找到了编译器选项:CompilerParameters cp = new CompilerParameters(); cp.CompilerOptions = "/优化 /target:winexe /win32icon:program.ico";谢谢!
    • 小注:似乎 VS 调试器偶尔会启动控制台程序而没有正确显示其图标。但不影响实际程序;这可能只是因为它被包装在调试器或其他东西中。
    【解决方案3】:

    这里是通过代码更改图标的解决方案:

    class IconChanger
    {
        public static void SetConsoleIcon(string iconFilePath)
        {
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                if (!string.IsNullOrEmpty(iconFilePath))
                {
                    System.Drawing.Icon icon = new System.Drawing.Icon(iconFilePath);
                    SetWindowIcon(icon);
                }
            }
        }
        public enum WinMessages : uint
        {
            /// <summary>
            /// An application sends the WM_SETICON message to associate a new large or small icon with a window. 
            /// The system displays the large icon in the ALT+TAB dialog box, and the small icon in the window caption. 
            /// </summary>
            SETICON = 0x0080,
        }
    
        [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
        private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, IntPtr lParam);
    
    
        private static void SetWindowIcon(System.Drawing.Icon icon)
        {
            IntPtr mwHandle = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
            IntPtr result01 = SendMessage(mwHandle, (int)WinMessages.SETICON, 0, icon.Handle);
            IntPtr result02 = SendMessage(mwHandle, (int)WinMessages.SETICON, 1, icon.Handle);
        }// SetWindowIcon()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-18
      • 1970-01-01
      • 2021-11-14
      • 2011-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-08
      相关资源
      最近更新 更多