C#“锁定”的覆盖形式到另一个窗口的位置(C# “Lock” an overlay form to

2019-08-07 13:11发布

我想提出一个为游戏添加上,但我希望它驻留作为覆盖了游戏的客户端窗口的区域。

基本上当我开始补充,我希望它显示在游戏的顶部。 美中不足的是,如果你最小化或移动窗口,我要的形式坚持下去。

任何人都知道的事情可以做的伎俩,而不必挂钩的DirectDraw?

谢谢。

Answer 1:

这里有一个简单的方法来做到这一点。 首先,你需要在你的窗体的使用说明这条线:

using System.Runtime.InteropServices;

接下来,添加这些声明,以您的形式:

[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);

接下来,您的表单TopMost属性设置为True。 最后,一个Timer控件添加到您的形式,其间隔属性设置为250和它的Enabled属性为True,并把这个代码在Tick事件:

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);
}

此代码将继续定位在游戏中的表格形式,如果游戏没有最小化,或者它也将最大限度地减少你的表格,如果比赛被最小化。 要更改应用程序的相对位置,只是改变在最后一行的“+ 10”的价值观。

更复杂的方法会涉及挂钩Windows消息以确定当游戏形式最大限度地减少或移动或改变大小,但这种轮询方法将实现几乎相同的事情更加简单。

最后一个位 :FindWindow函数将返回0,如果它发现与名称,没有窗户,所以你可以用这个游戏时关闭,关闭自己的应用程序。



文章来源: C# “Lock” an overlay form to the position of another window
标签: c# forms overlay