Batch command to change an icon of the currently running window

时光总嘲笑我的痴心妄想 提交于 2020-06-29 04:25:11

问题


In my working environment I can have up to 10 command prompt windows open, each one set up to work in a different context. Having all of them open, I find myself having to switch between several of them to find the right one that I want to work with.

I am already setting different foreground and background colors of each window based on some criteria, but it would be much more easier to distinguish between them by having a different colored icon in the taskbar. That way, I would not even have to maximize/bring them to focus to find the right one from the get-go.

Is there a way that I can change the taskbar icon of the currently running command prompt window programmatically by executing batch commands in it?


回答1:


There is no "built-in" way to do that, like there is the color command from cmd.exe to change the colors.

You could either search the internet for some utilitiy, or roll your own, for example in C#, by invoking the SetConsoleIcon Win32 API. Note however, that this API is not officially documented, YMMV.

using System;
using System.Drawing;
using System.Runtime.InteropServices;

class Program
{
    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern uint SetConsoleIcon(IntPtr iconHandle);

    static void Main(string[] args)
    {
        if (args[0].Equals("--reset", StringComparison.OrdinalIgnoreCase))
        {
            SetConsoleIcon(IntPtr.Zero);
        }
        else
        {
            // Use this to load an icon from an icon file instead:
            //   var icon = new Icon(args[0]); // load from .ico file
            // Extract icon from given executable/dll.
            using (var icon = Icon.ExtractAssociatedIcon(args[0]))
            {
                if (icon != null)
                    SetConsoleIcon(icon.Handle);
            }
        }
    }
}

You should be able to compile this using csc.exe setconico.cs (assuming you named the file setconico.cs). This will generate setconico.exe, which you can use like this:

Set the current console icon of the console you run this in, to the icon of notepad.exe

c:\> setconico.exe c:\windows\notepad.exe

You might also be able to write the above code in PowerShell, if you don't want to compile a separate utility.



来源:https://stackoverflow.com/questions/53185650/batch-command-to-change-an-icon-of-the-currently-running-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!