切换到另一个正在运行的进程

发布于 2024-12-06 07:40:03 字数 585 浏览 2 评论 0原文

有人可以解释一下我将如何通过 C# 切换到另一个正在运行的程序吗?

例如,如果我创建一个带有按钮事件的新应用程序 - 我想使用该按钮来调用一个打开的应用程序,例如 Internet Explorer 或 Word。

我知道如何启动应用程序,但不太确定如何在它们已经运行时调用它们。

这是迄今为止我们一直在努力的事情:

    if (System.Diagnostics.Process.GetProcessesByName("ExternalApplication").Length >= 1)
    {
        foreach (Process ObjProcess in System.Diagnostics.Process.GetProcessesByName("ExternalApplication"))
        {
            ActivateApplication(ObjProcess.Id);
            Interaction.AppActivate(ObjProcess.Id);
            SendKeys.SendWait("~");
        }
    }

Can someone please explain how I would go about switching to another running program via C#?

For example if i create a new application with a button event - i would like to use the button to say call an open application like internet explorer or word.

I know how to start applications but not quite sure how to call them when they are already running.

This is what have been working on so far:

    if (System.Diagnostics.Process.GetProcessesByName("ExternalApplication").Length >= 1)
    {
        foreach (Process ObjProcess in System.Diagnostics.Process.GetProcessesByName("ExternalApplication"))
        {
            ActivateApplication(ObjProcess.Id);
            Interaction.AppActivate(ObjProcess.Id);
            SendKeys.SendWait("~");
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

欢烬 2024-12-13 07:40:03

我必须解决类似的问题,并且我必须执行一些 pInvoking 才能完成它。请参阅下面的代码。

delegate bool EnumWindowsProc(IntPtr hWnd, int lParam);
public static class WindowEnumerator
{
    [DllImport("user32.dll", SetLastError = true)]
    private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

    [DllImport("USER32.DLL")]
    private static extern bool EnumWindows(EnumWindowsProc enumFunc, int lParam);

    [DllImport("USER32.DLL")]
    private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

    [DllImport("USER32.DLL")]
    private static extern int GetWindowTextLength(IntPtr hWnd);

    [DllImport("USER32.DLL")]
    private static extern bool IsWindowVisible(IntPtr hWnd);

    [DllImport("USER32.DLL")]
    private static extern IntPtr GetShellWindow();

    public static IDictionary<IntPtr, string> GetOpenWindowsFromPID(int processID)
    {
        IntPtr hShellWindow = GetShellWindow();
        Dictionary<IntPtr, string> dictWindows = new Dictionary<IntPtr, string>();

        EnumWindows(delegate(IntPtr hWnd, int lParam)
                    {
                        if (hWnd == hShellWindow) return true;
                        if (!IsWindowVisible(hWnd)) return true;

                        int length = GetWindowTextLength(hWnd);
                        if (length == 0) return true;

                        uint windowPid;
                        GetWindowThreadProcessId(hWnd, out windowPid);
                        if (windowPid != processID) return true;

                        StringBuilder stringBuilder = new StringBuilder(length);
                        GetWindowText(hWnd, stringBuilder, length + 1);
                        dictWindows.Add(hWnd, stringBuilder.ToString());
                        return true;
                    }, 0);

        return dictWindows;
    }
}

...

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

...

Process yourProcess = ???;

Dictionary<IntPtr, string> windows = (Dictionary<IntPtr, string>)WindowEnumerator.GetOpenWindowsFromPID(yourProcess.Id);
IntPtr mainWindowHandle = IntPtr.Zero;
foreach (KeyValuePair<IntPtr, string> pair in windows)
{
    if (pair.Value.ToUpperInvariant() == "Main Window Title")
    {
        mainWindowHandle = pair.Key;
        break;
    }
}

if (mainWindowHandle != IntPtr.Zero)
{
    if (IsIconic(mainWindowHandle))
    {
        ShowWindow(mainWindowHandle, 9);
    }
    SetForegroundWindow(mainWindowHandle);
}

I had to solve a similar problem, and I had to do some pInvoking to get it done. See code below.

delegate bool EnumWindowsProc(IntPtr hWnd, int lParam);
public static class WindowEnumerator
{
    [DllImport("user32.dll", SetLastError = true)]
    private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

    [DllImport("USER32.DLL")]
    private static extern bool EnumWindows(EnumWindowsProc enumFunc, int lParam);

    [DllImport("USER32.DLL")]
    private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

    [DllImport("USER32.DLL")]
    private static extern int GetWindowTextLength(IntPtr hWnd);

    [DllImport("USER32.DLL")]
    private static extern bool IsWindowVisible(IntPtr hWnd);

    [DllImport("USER32.DLL")]
    private static extern IntPtr GetShellWindow();

    public static IDictionary<IntPtr, string> GetOpenWindowsFromPID(int processID)
    {
        IntPtr hShellWindow = GetShellWindow();
        Dictionary<IntPtr, string> dictWindows = new Dictionary<IntPtr, string>();

        EnumWindows(delegate(IntPtr hWnd, int lParam)
                    {
                        if (hWnd == hShellWindow) return true;
                        if (!IsWindowVisible(hWnd)) return true;

                        int length = GetWindowTextLength(hWnd);
                        if (length == 0) return true;

                        uint windowPid;
                        GetWindowThreadProcessId(hWnd, out windowPid);
                        if (windowPid != processID) return true;

                        StringBuilder stringBuilder = new StringBuilder(length);
                        GetWindowText(hWnd, stringBuilder, length + 1);
                        dictWindows.Add(hWnd, stringBuilder.ToString());
                        return true;
                    }, 0);

        return dictWindows;
    }
}

...

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

...

Process yourProcess = ???;

Dictionary<IntPtr, string> windows = (Dictionary<IntPtr, string>)WindowEnumerator.GetOpenWindowsFromPID(yourProcess.Id);
IntPtr mainWindowHandle = IntPtr.Zero;
foreach (KeyValuePair<IntPtr, string> pair in windows)
{
    if (pair.Value.ToUpperInvariant() == "Main Window Title")
    {
        mainWindowHandle = pair.Key;
        break;
    }
}

if (mainWindowHandle != IntPtr.Zero)
{
    if (IsIconic(mainWindowHandle))
    {
        ShowWindow(mainWindowHandle, 9);
    }
    SetForegroundWindow(mainWindowHandle);
}
彡翼 2024-12-13 07:40:03

下面的代码对我有用

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace SingleInstanceWindow
{
static class Program
{
    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool SetForegroundWindow(IntPtr hWnd);
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        var me = Process.GetCurrentProcess();
        var arrProcesses = Process.GetProcessesByName(me.ProcessName);
        if (arrProcesses.Length > 1)
        {
            SetForegroundWindow(arrProcesses[0].MainWindowHandle);
            return;
        }

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}
}

如果窗口最小化,上面的代码将不起作用

代码:

[DllImport("user32.dll")]
public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);

用法:

SwitchToThisWindow(arrProcesses[0].MainWindowHandle, true);

below code worked for me

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace SingleInstanceWindow
{
static class Program
{
    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool SetForegroundWindow(IntPtr hWnd);
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        var me = Process.GetCurrentProcess();
        var arrProcesses = Process.GetProcessesByName(me.ProcessName);
        if (arrProcesses.Length > 1)
        {
            SetForegroundWindow(arrProcesses[0].MainWindowHandle);
            return;
        }

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}
}

above code doesn't work if window is minimized

code:

[DllImport("user32.dll")]
public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);

usage:

SwitchToThisWindow(arrProcesses[0].MainWindowHandle, true);
时光匆匆的小流年 2024-12-13 07:40:03

我正在使用以下内容,但我认为没有在第 31 行正确定义进程名称。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace test_winform_app
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

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

        private void button1_Click(object sender, EventArgs e)
        {

            Process yourProcess = Process.GetProcessesByName("notepad");

Dictionary<IntPtr, string> windows = (Dictionary<IntPtr, string>)WindowEnumerator.GetOpenWindowsFromPID(yourProcess.Id);
IntPtr mainWindowHandle = IntPtr.Zero;
foreach (KeyValuePair<IntPtr, string> pair in windows)
{
    if (pair.Value.ToUpperInvariant() == "Main Window Title")
    {
        mainWindowHandle = pair.Key;
        break;
    }
}

if (mainWindowHandle != IntPtr.Zero)
{
    if (IsIconic(mainWindowHandle))
    {
        ShowWindow(mainWindowHandle, 9);
    }
    SetForegroundWindow(mainWindowHandle);
}
        }

        delegate bool EnumWindowsProc(IntPtr hWnd, int lParam);
        public static class WindowEnumerator
        {
            [DllImport("user32.dll", SetLastError = true)]
            private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

            [DllImport("USER32.DLL")]
            private static extern bool EnumWindows(EnumWindowsProc enumFunc, int lParam);

            [DllImport("USER32.DLL")]
            private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

            [DllImport("USER32.DLL")]
            private static extern int GetWindowTextLength(IntPtr hWnd);

            [DllImport("USER32.DLL")]
            private static extern bool IsWindowVisible(IntPtr hWnd);

            [DllImport("USER32.DLL")]
            private static extern IntPtr GetShellWindow();

            public static IDictionary<IntPtr, string> GetOpenWindowsFromPID(int processID)
            {
                IntPtr hShellWindow = GetShellWindow();
                Dictionary<IntPtr, string> dictWindows = new Dictionary<IntPtr, string>();

                EnumWindows(delegate(IntPtr hWnd, int lParam)
                {
                    if (hWnd == hShellWindow) return true;
                    if (!IsWindowVisible(hWnd)) return true;

                    int length = GetWindowTextLength(hWnd);
                    if (length == 0) return true;

                    uint windowPid;
                    GetWindowThreadProcessId(hWnd, out windowPid);
                    if (windowPid != processID) return true;

                    StringBuilder stringBuilder = new StringBuilder(length);
                    GetWindowText(hWnd, stringBuilder, length + 1);
                    dictWindows.Add(hWnd, stringBuilder.ToString());
                    return true;
                }, 0);

                return dictWindows;
            }
        }
    }
}

I am using the following but i dont think have defined the process name correctly on line 31.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace test_winform_app
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

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

        private void button1_Click(object sender, EventArgs e)
        {

            Process yourProcess = Process.GetProcessesByName("notepad");

Dictionary<IntPtr, string> windows = (Dictionary<IntPtr, string>)WindowEnumerator.GetOpenWindowsFromPID(yourProcess.Id);
IntPtr mainWindowHandle = IntPtr.Zero;
foreach (KeyValuePair<IntPtr, string> pair in windows)
{
    if (pair.Value.ToUpperInvariant() == "Main Window Title")
    {
        mainWindowHandle = pair.Key;
        break;
    }
}

if (mainWindowHandle != IntPtr.Zero)
{
    if (IsIconic(mainWindowHandle))
    {
        ShowWindow(mainWindowHandle, 9);
    }
    SetForegroundWindow(mainWindowHandle);
}
        }

        delegate bool EnumWindowsProc(IntPtr hWnd, int lParam);
        public static class WindowEnumerator
        {
            [DllImport("user32.dll", SetLastError = true)]
            private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

            [DllImport("USER32.DLL")]
            private static extern bool EnumWindows(EnumWindowsProc enumFunc, int lParam);

            [DllImport("USER32.DLL")]
            private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

            [DllImport("USER32.DLL")]
            private static extern int GetWindowTextLength(IntPtr hWnd);

            [DllImport("USER32.DLL")]
            private static extern bool IsWindowVisible(IntPtr hWnd);

            [DllImport("USER32.DLL")]
            private static extern IntPtr GetShellWindow();

            public static IDictionary<IntPtr, string> GetOpenWindowsFromPID(int processID)
            {
                IntPtr hShellWindow = GetShellWindow();
                Dictionary<IntPtr, string> dictWindows = new Dictionary<IntPtr, string>();

                EnumWindows(delegate(IntPtr hWnd, int lParam)
                {
                    if (hWnd == hShellWindow) return true;
                    if (!IsWindowVisible(hWnd)) return true;

                    int length = GetWindowTextLength(hWnd);
                    if (length == 0) return true;

                    uint windowPid;
                    GetWindowThreadProcessId(hWnd, out windowPid);
                    if (windowPid != processID) return true;

                    StringBuilder stringBuilder = new StringBuilder(length);
                    GetWindowText(hWnd, stringBuilder, length + 1);
                    dictWindows.Add(hWnd, stringBuilder.ToString());
                    return true;
                }, 0);

                return dictWindows;
            }
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文