Garrett Guilbault
Garrett Guilbault

Reputation: 55

Displaying an overlay above another program

I have a program to display some additional information in a third party application. Originally, the third party application had a simple API that allowed me to create text objects; but it's since been removed in a version update. Using the legacy version is not an option.

Is there an easy way to do this? I basically just want a few lines of easily updatable text that are positioned relative to the host window, have a transparent background, minimize with the host window, and do not interfere with the host window's processing of keystrokes or mouse.

Apologies if this isn't the appropriate place to ask this question, I did search the site but I couldn't find anything that seemed to fit my needs.

Upvotes: 3

Views: 7879

Answers (1)

Icemanind
Icemanind

Reputation: 48726

There is not an easy way to do this, mainly because each process runs in its own memory space. However, you can "fake" it sort of. The first thing you need to do is find the handle to the window:

Process[] processes = Process.GetProcessesByName("appName");

Process p = processes.FirstOrDefault();
IntPtr windowHandle;
if (p != null)
{
    windowHandle = p.MainWindowHandle;
}

Now once you have the handle, you can get the area of the screen that the window resides:

[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
    public int Left;
    public int Top;
    public int Right;
    public int Bottom;
}

RECT rect = new RECT();
GetWindowRect(windowHandle, ref rect);

This will give you the location of the window. One thing to note is if the application is minimized when you run this, you will get values such as -32000. If you are interested in knowing why, you can read this. Now that you have the location of the window, in your application, you can resize your application's form to the same size as the other application and position it over the application:

this.Location = new Point(rect.Left, rect.Top);
this.Size = new Size(rect.Right - rect.Left, rect.Bottom - rect.Top);

Now your application is directly over the other application and is resized to the same size as the other application. Finally, you need to make your application "transparent":

this.BackColor = Color.LimeGreen;
this.TransparencyKey = Color.LimeGreen;
this.FormBorderStyle = FormBorderStyle.None;

This should do it, though I haven't tested it. You can add any Text Boxes or Labels you may need to your form and it will "overlay" the application. Hope this works for you!

Upvotes: 8

Related Questions