选择一个表单时,使与程序关联的所有表单都出现在前面

Sco*_*ain 4 .net c# .net-4.0 winforms

我在我的应用程序有两种形式MainFormHexCompare.如果我点击我的应用程序到另一个窗口然后我点击两个表单中的一个,只有其中一个来到前面.如果我单击两个表单中的任何一个表单,它将如何使其成为应用程序中所有打开表单的顶部?现在我需要单独选择每个表单以使它们到我的窗口堆栈的顶部(这可能非常烦人,因为HexCompare已经ShowInTaskbar设置为false

一个很好的例子就是我想要的方式是大多数查找对话框的工作方式.如果单击查找对话框,则如果主窗体被另一个应用程序隐藏,则它会将主窗体带到前面;如果单击主窗体,则如果另一个应用程序隐藏了查找对话框,则它将出现在前面.

如何MainForm调用.

[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new MainForm());
}
Run Code Online (Sandbox Code Playgroud)

如何HexCompare调用

private void lstCaputres_SelectedIndexChanged(object sender, EventArgs e)
{
    var selectedItem = (Tuple<DateTime, byte[]>)lstCaputres.SelectedItem;
    if (hexCompare == null || hexCompare.IsDisposed)
    {
        hexCompare = new HexCompare(selectedItem.Item2);
        hexCompare.Show();
    }
    else
        hexCompare.ChangeValue(selectedItem.Item2);
}
Run Code Online (Sandbox Code Playgroud)

编辑:

似乎HexCompare价值ParentNull.如果我能以某种方式设置它来MainForm解决我的问题,如果是这样我该怎么设置它?

EDIT2:

我已经使用Tigran的解决方案对其进行了半解决,但是如果有更好的解决方案我仍然感兴趣,它会导致闪烁,因为每个表单都会被带到前面.

//In MainForm.cs
private void MainForm_Activated(object sender, EventArgs e)
{
    hexCompare.BringToFront();
    this.BringToFront();
}

//in HexCompare.cs
private void HexCompare_Activated(object sender, EventArgs e)
{
    parent.BringToFront();
    this.BringToFront();
}
Run Code Online (Sandbox Code Playgroud)

A. *_*son 5

您可以使用以下API包装器将表单放在z顺序的前面,而不会将其转移到焦点上.可以在主窗体的Activated事件中调用此函数,只需将HexCompare窗体作为参数传递给它即可.这不是从对方的回答不同,但正如你在评论中提到我从来没有看到任何闪烁.

  private const int SW_SHOWNOACTIVATE = 4;
  private const int HWND_TOPMOST = 0;
  private const uint SWP_NOACTIVATE = 0x0010;

  [DllImport("user32.dll", EntryPoint = "SetWindowPos")]
  static extern bool SetWindowPos(
       int hWnd,           // window handle 
       int hWndInsertAfter,    // placement-order handle 
       int X,          // horizontal position 
       int Y,          // vertical position 
       int cx,         // width 
       int cy,         // height 
       uint uFlags);       // window positioning flags 

  [DllImport("user32.dll")]
  static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

  public void ShowInactiveTopmost(Form frm)
  {
     ShowWindow(frm.Handle, SW_SHOWNOACTIVATE);
     SetWindowPos(frm.Handle.ToInt32(), HWND_TOPMOST,
     frm.Left, frm.Top, frm.Width, frm.Height,
     SWP_NOACTIVATE);
  }
Run Code Online (Sandbox Code Playgroud)