C#控制台应用程序图标

kal*_*l3v 22 c# console-application imageicon

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

小智 25

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

请参阅此Stack Overflow文章:是否可以从.net更改控制台窗口的图标?

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

  • 我们是否只是忽略OP明确表示他们想要一种方法在代码中做到这一点......不是来自项目属性? (7认同)
  • 这提供了我正在寻找的解决方案。也许不是 OP 要求的 (3认同)

Jon*_*eet 23

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

/win32icon:<file>如果有任何帮助,请使用命令行,但不能在应用程序的代码中指定它.不要忘记,大多数时候显示应用程序的图标,您的应用程序根本不运行!

假设您在资源管理器中表示文件本身的图标.如果您只是双击该文件,则表示应用程序在运行时的图标,我相信它始终只是控制台本身的图标.

  • 我找到了编译器选项:CompilerParameters cp = new CompilerParameters(); cp.CompilerOptions ="/ optimize/target:winexe /win32icon:program.ico"; 谢谢! (8认同)
  • 小方注意:似乎VS调试器偶尔启动控制台程序而没有正确显示其图标.但它并不影响实际的计划; 它可能只是因为它被包装在调试器或其他东西中. (2认同)

小智 6

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

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()
}
Run Code Online (Sandbox Code Playgroud)