问题描述
我想做的事情很简单:将WinForm放在另一个之上,而不是最顶层.就像,当我单击一个窗口时,我的winform会在它的顶部,但是当我单击其他东西(例如浏览器)时,我的窗体将不在它的顶部.
What I'm trying to do is simple: make my WinForm on top of another, but not topmost.Like, when I click on a window, my winform will be on top of it, but when I click on something else, like a browser, my form will not be on top of it.
类似于TopMost WinForm,但仅适用于特定过程.(我正在为游戏制作叠加层,所以我需要它在游戏中位于最高位置.)
Like a TopMost WinForm, but only for a specific process.(Im making a overlay for a game, so I need it to be topmost ONLY on the game.)
有帮助的图片(红色边框内的所有内容都是我的形式):
Pictures to help (Everything inside the RED border is my form):
然后,当我切换到另一个窗口(在本例中为Explorer)时,我希望表单位于背景中,就像《英雄联盟》客户端
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 client
推荐答案
所拥有的表单始终显示在其所有者表单的顶部.要使表单归所有者所有,可以将所有者表单的引用分配给拥有表单的 Onwer
属性,例如:
Owned forms are always displayed on top of their owner form. To make a form owned by an owner, you can assign a reference of the owner form to Onwer
property of the owned form, for example:
var f = new Form();
f.Owner = this;
f.Show();
将另一个进程的窗口设置为所有者
为此,您应该首先找到另一个进程的窗口句柄,然后使用 SetWindowLong
API函数,您可以将其设置为以下内容的所有者您的表格,例如:
To do so, you should first find the handle of window of the other process, then using SetWindowLong
API function, you can set it as owner of your form, for example:
//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);
}
}
在上面的示例中,您的表单将始终位于记事本窗口的顶部.
In above example, your form will be always on top of the notepad window.
这篇关于是否可以将一个表单放在另一个表单之上,而不是在TopMost之上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!