c#正在运行的程序的焦点窗口

时间:2014-08-30 01:54:27

标签: c# setfocus user32

我想从我的c#application.i搜索很多关注程序并找到一些例子。但是我得到了错误。我正在使用visual studio。ShowWindow(hWnd, SW_HIDE);行给了我一个错误"showwindow(system.IntPtr,int) has some invalid argument" 请问这段代码的问题在哪里

[DllImport("user32.dll")]
        internal static extern IntPtr SetForegroundWindow(IntPtr hWnd);

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

 private void FocusProcess()
        {
            int hWnd;
            Process[] processRunning = Process.GetProcesses();
            foreach (Process pr in processRunning)
            {
                if (pr.ProcessName == "notepad")
                {
                    hWnd = pr.MainWindowHandle.ToInt32();
                    ShowWindow(hWnd, 3);//error line
                }
            }
        }

1 个答案:

答案 0 :(得分:1)

您将hWnd声明为int。但是ShowWindow函数需要一个IntPtr。因为pr.MainWindowHandle是一个IntPtr,你只需要将它用作hWnd。 顺便说一句。如果你想把这个窗口作为最顶层,你应该调用SetForegroundWindow。

    [DllImport("user32.dll")]
    internal static extern IntPtr SetForegroundWindow(IntPtr hWnd);

    [DllImport("user32.dll")]
    internal static extern bool ShowWindow(IntPtrhWnd, int nCmdShow); //ShowWindow needs an IntPtr

    private static void FocusProcess()
    {
        IntPtr hWnd; //change this to IntPtr
        Process[] processRunning = Process.GetProcesses();
        foreach (Process pr in processRunning)
        {
            if (pr.ProcessName == "notepad")
            {
                hWnd = pr.MainWindowHandle; //use it as IntPtr not int
                ShowWindow(hWnd, 3);
                SetForegroundWindow(hWnd); //set to topmost
            }
        }
    }