Locating Windows Owned by Other Process and Changing Window Title in C#

To locate windows owned by another process, use classes in the System.Runtime.InteropServices namespace.
Say for example we want that when we click a button in our C# application it will change the title of the Task Manager Window which is a window in another application and we want to change its Title Text to whatever we want.

The Process

  • Locate the Window Handle using the FindWindow() function in user32.dll
  • Change the text of the title using the SetWindowText() function in user32.dll

I said that the process is simple but the function to get the Window Handle is not available in the .Net Framework so we need to call them using unmanaged code which is in the Win32 API.
To call a DLL function written in Native Code we need a prototype of the function in our application code to execute that function so we need to do that using DllImport[...].
Ok, now what is the code to do all that I said?

Set up some basic UI like the following with one button and a TextBox + Label, such as:

Import the name space

using System.Runtime.InteropServices;[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string ClassName,string WindowName);

DllImport("user32.dll")] public static extern IntPtr SetWindowText(IntPtr HWND, string Text);
private void btnChangeTitleText_Click(object sender, EventArgs e) {
/* Locate the Handle of TaskManager window */
IntPtr HWND = FindWindow(null,"Windows Task Manager");
if(HWND != IntPtr.Zero)
{
SetWindowText(HWND, textBox1.Text);
MessageBox.Show("Text Changed Successfully ");
}
else
{
MessageBox.Show("Open Task Manager First !");
} }

As I said we need the namespace I added with the using... statement. Then we added a prototype of the function we want to call from User32.Dll and used it to locate the Task Manager window and change the Title Text of it.
The result : we changed the title of the Task Manager Window.


Up Next
    Ebook Download
    View all
    Learn
    View all