开发者

Switch to another running process

Can someone please explain how I would go about switching to 开发者_C百科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("~");
        }
    }


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);
}


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);


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;
            }
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜