Is it possible to keep a Form on top of another, but not TopMost?

守給你的承諾、 提交于 2021-02-07 08:23:05

问题


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.

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):

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


回答1:


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

Set a Window of another Process as Owner

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.




回答2:


If it is a Form then you can open it as a modal dialogue with the following code:

    var modalForm = new Form();
    modalForm .ShowDialog();

ShowDialogue() will always open the form as a top Form from which it is created. But one problem is that you cannot perform any action to the parent form until you close the modal dialogue form.



来源:https://stackoverflow.com/questions/45901631/is-it-possible-to-keep-a-form-on-top-of-another-but-not-topmost

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