简体   繁体   English

运行程序的C#焦点窗口

[英]c# focus window of a runing program

i want to focus a program from my c# application.i searched lot and found some examples.but i got error .i'm using visual studio. 我想从我的C#应用​​程序集中一个程序。我搜索了很多并找到了一些示例。但是我遇到了错误。我正在使用Visual Studio。 ShowWindow(hWnd, SW_HIDE); line gives me an error "showwindow(system.IntPtr,int) has some invalid argument" plz where is the problem of this code 这行给我一个错误"showwindow(system.IntPtr,int) has some invalid argument" plz该代码的问题在哪里?

[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
                }
            }
        }

You declared hWnd as int. 您将hWnd声明为int。 But the ShowWindow function needs an IntPtr. 但是ShowWindow函数需要一个IntPtr。 Because pr.MainWindowHandle is an IntPtr you just need to use it as hWnd. 因为pr.MainWindowHandle是IntPtr,所以只需要将其用作hWnd。 Btw. 顺便说一句。 if you want this window as the topmost you should call SetForegroundWindow. 如果您希望此窗口位于最顶层,则应调用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
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM