Thursday 17 February 2011

Manipulating applications window from .NET application

One of my colleagues was "hacking" a third party application by placing his own .NET application partly over it, at the specific coordinates. To do this he needed to be able to find third party application and set its window position and size on the fly from his .NET app. So I coded a DLL for him.

First I needed to find the window:
public static bool FindApplicationByWindowName(string AppName)
{
int bRtn = 0;

foreach (Process p in Process.GetProcesses("."))
{
try
{
if (p.MainWindowTitle.ToString().ToLower() == AppName.ToLower())
{
bRtn = p.MainWindowHandle.ToInt32();
}
}
catch { }
}
return bRtn;
}



Next thing was to move and change size. For this I used various methods like MaximiseThisWindow method below:

public static bool MaximiseThisWindow(string AppName)
{
bool bRtn = false;
int wHandle = FindApplicationByWindowName(AppName);

if (wHandle > 0)
{
ShowWindow(wHandle, SW_MAXIMIZE);
bRtn = true;
}

return bRtn;
}

Notice imported User32 function ShowWindow used to maximise the window. You need to include the code below to be able to use it:
private const int SW_MAXIMIZE = 3;

[DllImport("User32")]
private static extern int ShowWindow(int hwnd, int nCmdShow);

Also don't forget to include the System.Runtime.InteropServices namespace.

No comments: