是否可以将一个表单保留在另一个表单之上,但不能保留在 TopMost 之上?

2024-02-04

我想做的很简单:让我的 WinForm 位于另一个之上,但不是最顶层。 就像,当我单击一个窗口时,我的 winform 将位于其顶部,但是当我单击其他内容(例如浏览器)时,我的窗体将不会位于其顶部。

与 TopMost WinForm 类似,但仅适用于特定进程。 (我正在为游戏制作叠加层,所以我需要它仅在游戏中位于最顶层。)

Pictures to help (Everything inside the RED border is my form):enter image description here

And then when I change to another window (In this case, Explorer) I want my form to be in the background, just like the League of Legends cliententer image description here


拥有的表单始终显示在其所有者表单的顶部。要使表单归所有者所有,您可以将所有者表单的引用分配给Onwer https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwindowlonga?WT.mc_id=DT-MVP-5003235拥有的表单的属性,例如:

var f = new Form();
f.Owner = this;
f.Show();

将另一个进程的窗口设置为所有者

为此,您应该首先找到其他进程的窗口句柄,然后使用API函数,您可以将其设置为表单的所有者,例如:

//using System.Runtime.InteropServices;
//using System.Diagnostics;

[DllImport("user32.dll", EntryPoint = "SetWindowLong", CharSet = CharSet.Auto)]
public static extern IntPtr SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
private void button1_Click(object sender, EventArgs e)
{
    var notepad = Process.GetProcessesByName("notepad").FirstOrDefault();
    if(notepad!=null)
    {
        var owner = notepad.MainWindowHandle;
        var owned = this.Handle;
        var i = SetWindowLong(owned, -8 /*GWL_HWNDPARENT*/, owner);
    }
}

在上面的示例中,您的表单将始终位于记事本窗口的顶部。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

是否可以将一个表单保留在另一个表单之上,但不能保留在 TopMost 之上? 的相关文章

随机推荐