C# GetForeGroundIndow引发Win32Exception访问被拒绝

C# GetForeGroundIndow引发Win32Exception访问被拒绝,c#,window-handles,rundll32,C#,Window Handles,Rundll32,我已经尝试以管理员的身份运行该应用程序,无法运行。 我在这里做错了什么,所以我得到了这个异常?结果表明,我所做的整个循环也在受保护的进程上,这导致访问被拒绝枚举进程从来都不是一个好主意。改用GetWindowThreadProcessId()。@HansPassant将其转换为答案,我将向上投票;-) public partial class Form1 : Form { [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpel

我已经尝试以管理员的身份运行该应用程序,无法运行。
我在这里做错了什么,所以我得到了这个异常?

结果表明,我所做的整个循环也在受保护的进程上,这导致访问被拒绝

枚举进程从来都不是一个好主意。改用GetWindowThreadProcessId()。@HansPassant将其转换为答案,我将向上投票;-)
public partial class Form1 : Form
{
    [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
    private static extern IntPtr GetForegroundWindow();

    public Form1()
    {
        InitializeComponent();
        var proc = Process.GetProcesses().Single(x => x.Handle == GetForegroundWindow());
    }
}