C# 窗体置顶

实例链接:Windows窗体置顶C#/wpf编程-C#文档类资源-CSDN下载 

//引用
using System.Runtime.InteropServices;
using System.Windows.Interop;

//GetActiveWindow返回线程的活动窗口,而不是系统的活动窗口。如果要得到用户正在激活的窗口,应该使用 GetForegroundWindow
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetForegroundWindow();

[DllImport("user32.dll ")]
//设置窗体置顶
private static extern bool SetForegroundWindow(IntPtr hWnd);

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

//窗体句柄
private IntPtr handle = IntPtr.Zero;
public IntPtr Handle { get => handle; set => handle = value; }



private void Window_Loaded(object sender, RoutedEventArgs e)
{
        //方法一 
        handle = new WindowInteropHelper(this).Handle;
        SetForegroundWindow(handle);
        ShowWindow(handle, 3);
        
        //SetFormForeground("iexplore");
}

//方法二,查找进程并置顶
private void SetFormForeground(string processName)
{
    Process[] localByName = Process.GetProcessesByName(processName);
    foreach (Process proc in localByName)
    {
        if (proc.MainWindowTitle != string.Empty)
        {
            IntPtr handle = proc.MainWindowHandle;
            SetForegroundWindow(handle);
            ShowWindow(handle, 3);
        }
    }
}

你可能感兴趣的:(C#,WPF,c#,windows,.net)