簡體   English   中英

C# 控制台應用程序圖標

[英]C# console application icon

有誰知道如何在代碼中設置 C# 控制台應用程序的圖標(不使用 Visual Studio 中的項目屬性)?

您可以在項目屬性中更改它。

請參閱這篇 Stack Overflow 文章: Is it possible to change a console window's icon from .net?

總結一下,在 Visual Studio 中右鍵單擊您的項目(不是解決方案)並選擇屬性。 在“應用程序”選項卡的底部有一個“圖標和清單”部分,您可以在其中更改圖標。

您不能在代碼中指定可執行文件的圖標 - 它是二進制文件本身的一部分。

如果有幫助,您可以從命令行使用/win32icon:<file> ,但您不能在應用程序代碼中指定它。 不要忘記,大部分時間顯示應用程序的圖標,您的應用程序根本沒有運行!

假設您指的是資源管理器中文件本身的圖標。 如果您指的是應用程序運行時的圖標,只要雙擊該文件,我相信那將始終只是控制台本身的圖標。

這是通過代碼更改圖標的解決方案:

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()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM