Search code examples
c#processwindowtitlebar

C# - How can I rename a process window that I started?


Is there any way I can rename the window titlebar of an application that I've launched? I.e. if I launched Notepad.exe, I could rename its title bar from "Untitled - Notepad" to "New Notepad Name".


Solution

  • You can do it using P/Invoke:

    [DllImport("user32.dll")]
    static extern int SetWindowText(IntPtr hWnd, string text);
    
    
    
    private void StartMyNotepad()
    {
        Process p = Process.Start("notepad.exe");
        Thread.Sleep(100);  // <-- ugly hack
        SetWindowText(p.MainWindowHandle, "My Notepad");
    }
    

    The background of the ugly hack in the code sample is that it seems as if you call SetWindowText immediately after starting the process, the title will not change. Perhaps the message ends up too early in the message queue of Notepad, so that notepad will set the title again afterwards.

    Also note that this is a very brief change; if the user selects File -> New (or does anything else that will cause Notepad to update the window title), the original title will be back...