C# “Lock” an overlay form to the position of another window

倾然丶 夕夏残阳落幕 提交于 2019-12-05 03:08:18

问题


I am making an add on for a game, but I want it to reside as an overlay to the game's client area of the window.

Basically when I start the add on, i want it to show on top of the game. The catch is if you minimize or move the window, I want the the form to stick with it.

Anyone know of anything that can do the trick without having to hook directdraw?

Thanks.


回答1:


Here is a simple way to do this. First, you'll need this line in your form's using statements:

using System.Runtime.InteropServices;

Next, add these declarations to your form:

[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
    public int X;
    public int Y;
    public int Width;
    public int Height;
}

[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); 

[DllImport("user32.dll", SetLastError = true)]
public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);

Next, set your form's TopMost property to True. Finally, add a Timer control to your form, set its Interval property to 250 and its Enabled property to True, and put this code in its Tick event:

IntPtr hWnd = FindWindow(null, "Whatever is in the game's title bar");
RECT rect;
GetWindowRect(hWnd, out rect);
if (rect.X == -32000)
{
    // the game is minimized
    this.WindowState = FormWindowState.Minimized;
}
else
{
    this.WindowState = FormWindowState.Normal;
    this.Location = new Point(rect.X + 10, rect.Y + 10);
}

This code will keep your form positioned over the game's form if the game is not minimized, or it will minimize your form also if the game is minimized. To change the relative position of your application, just change the "+ 10" values in the last line.

The more complicated method would involve hooking windows messages to determine when the game form minimizes or moves or changes size, but this polling method will accomplish almost the same thing much more simply.

One last bit: FindWindow will return 0 if it finds no window with that title, so you could use this to close your own application when the game is closed.



来源:https://stackoverflow.com/questions/1442303/c-sharp-lock-an-overlay-form-to-the-position-of-another-window

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