简体   繁体   中英

C#: Microsoft.VisualBasic.Interaction.AppActivate no effect

My code is very simple:

using Microsoft.VisualBasic;
namespace HelloWorld { 
    class MyClass { 
        static void Main(string[] args) { 
            Interaction.AppActivate(6156); // the PID of notepad++
        } 
    } 
}

When I execute this program, nothing happens. I would expect 6156 (PID from Task Manager) aka Notepad++ to get focused. What's wrong here?

I'm trying to find the equivalent to Pythons pywin32 code of shell = win32com.client.Dispatch("WScript.Shell") and shell.AppActivate(6156)

The Interaction.AppActivate code will not work if the app is minimized. Use the following code to active the app:

    public const int SW_RESTORE = 9;

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

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

    static void Main(string[] args)
    {        
        var process = Process.GetProcessById(18036);
        ShowWindow(process.MainWindowHandle, SW_RESTORE);
        SetForegroundWindow(process.MainWindowHandle);
    }

This works fine for me.

    static void Main(string[] args)
    {
        var process = Process.GetProcessById(13004);//the pid
        if (process == null) return;
        SwitchToThisWindow(process.MainWindowHandle, true);
    }
    [DllImport("user32.dll", SetLastError = true)]
    static extern void SwitchToThisWindow(IntPtr hWnd, bool turnOn);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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