SetForegroundWindow doesn't work with minimized process [duplicate]

谁说我不能喝 提交于 2020-01-01 19:07:04

问题


Couldn't find any good answer on this topic, so maybe someone can help me out. I'm making a small personal program where I want to bring a certain application to the foreground. It already works, but there is one small problem. When the process is minimized my code doesn't work. The process won't get showed on the foreground like it does when it is not minimized.

Here is a snippet of the code:

public partial class Form1 : Form
{
    [DllImport("user32.dll")]
    static extern bool SetForegroundWindow(IntPtr hWnd);

    public Form1()
    {
       InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        System.Diagnostics.Process[] p
            = System.Diagnostics.Process.GetProcessesByName("Client");

        if (p.Length > 0)
        {
            SetForegroundWindow(p[0].MainWindowHandle);
        }
        else
        {
            MessageBox.Show("Window Not Found!");
        }
    }
}

回答1:


You are going to need to call ShowWindow before you try to set it as the foreground window.

Probably with SW_RESTORE:

 [DllImport("user32.dll")]
 [return: MarshalAs(UnmanagedType.Bool)]
 static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

 if (p.Length > 0)
 {
   ShowWindow(p[0].MainWindowHandle, 9);
   SetForegroundWindow(p[0].MainWindowHandle);
 }

PInvoke.net - ShowWindow has some examples on DllImport and using the function in C#.



来源:https://stackoverflow.com/questions/27449298/setforegroundwindow-doesnt-work-with-minimized-process

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