繁体   English   中英

如何从进程中还原隐藏的WPF窗口

[英]How to restore the hidden wpf window from process

在我的wpf窗口中,我隐藏了该窗口并将其从关闭的任务栏中删除。

我如何从正在运行的进程中激活该窗口。 我尝试了很多方法,但没有成功。

这是激活隐藏窗口的示例代码。

private void checkIfProcessRunning()
{           
    // get the name of our process
    string proc = Process.GetCurrentProcess().ProcessName;
    // get the list of all processes by that name
    Process[] processes = Process.GetProcessesByName(proc);
    // if there is more than one process...
    if (processes.Length > 1)
    {
    // Assume there is our process, which we will terminate, 
    // and the other process, which we want to bring to the 
    // foreground. This assumes there are only two processes 
    // in the processes array, and we need to find out which 
    // one is NOT us.
    RzLogger.WriteLine("process are running count:" + processes.Length);
        // get our process
        Process p = Process.GetCurrentProcess();
        int n = 0;        // assume the other process is at index 0
                          // if this process id is OUR process ID...
        if (processes[0].Id == p.Id)
        {
        RzLogger.WriteLine("other process are at 1");
        // then the other process is at index 1
        n = 1;
        }
        // get the window handle
        IntPtr hWnd = processes[n].MainWindowHandle;
    RzLogger.WriteLine("main handle is:" + hWnd);
        // if iconic, we need to restore the window
        if (IsIconic(hWnd))
        {
        RzLogger.WriteLine("is minimized");
        ShowWindowAsync(hWnd, SW_SHOWNORMAL);
        ShowWindowAsync(hWnd, SW_RESTORE);
        SetForegroundWindow(hWnd);

    }
    // bring it to the foreground
    SetForegroundWindow(hWnd);
    // exit our process
    Application.Current.Shutdown();
    return;
    }
    // ... continue with your application initialization here.

}

问题是我总是将句柄设置为0。

有没有办法做到这一点? 而且我不想在任务栏中显示任何内容

这是一个如何使用管道的示例。

除此之外,如果您快速启动实例,还可以使用命名的互斥锁(在这种情况下,您最终可能会拥有1台以上的服务器-因此,请尽早创建一个命名的互斥锁,如果存在的话,只需发送Show()在管道上并关闭。

从VS2017默认Wpf-Project创建。 编译它,启动Debug-Build,转到输出文件夹,然后再次启动exe以显示其功能。

MainWindow.xaml

<Window x:Class="interproc.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:interproc"
        mc:Ignorable="d"
        Title="MainWindow"
        Height="350"
        Width="525"
        Loaded="Window_Loaded">
    <Grid>
        <TextBlock Name="tb"
                   Background="Yellow"
                   Text="..."
                   Margin="50" />
    </Grid>
</Window>

MainWindow.xaml.cs

using System;
using System.Windows;
using System.IO.Pipes;
using System.Threading;
using System.Windows.Threading;

namespace InterprocessCommunicationViaPipes
{
    /// <summary>
    ///   Commands used to communiate via pipe 
    /// </summary>
    public enum EPipeCommands : byte
    {
        None, Show, Hide, Close
    };

    /// <summary>
    ///   Interaction logic for MainWindow.xaml 
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            Title = DateTime.UtcNow.ToString("o");
        }

        /// <summary>
        ///   Name of the pipe used for interprocess communication 
        /// </summary>
        private const string PipeName = "MyCoolApp";

        /// <summary>
        ///   prevents double Close() calls 
        /// </summary>
        private bool isClosing = false;

        /// <summary>
        ///   Server 
        /// </summary>
        private NamedPipeServerStream pipeServerStream = null;

        /// <summary>
        ///   Thread server is running in 
        /// </summary>
        private Thread ServerThread;

        void ActOnPipeCommand(EPipeCommands c)
        {
            Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, 
                new ThreadStart(
                delegate
                {
                    tb.Text += $"\n{DateTime.UtcNow:o} recieved {c}\n";

                    switch (c)
                    {
                        case EPipeCommands.None:
                            return;

                        case EPipeCommands.Hide:
                            Hide();
                            break;

                        case EPipeCommands.Show:
                            if (this.WindowState == WindowState.Minimized)
                                WindowState = WindowState.Normal;

                            Visibility = Visibility.Visible;
                            break;

                        case EPipeCommands.Close when !isClosing:
                            Close();
                            break;

                        case EPipeCommands.Close:
                            tb.Text += $"Already closing.\n";
                            break;

                        default:
                            tb.Text += $"Unmapped pipe action: {c.ToString()}\n";
                            break;
                    }
                }));
        }

        /// <summary>
        ///   Server running? 
        /// </summary>
        /// <returns></returns>
        bool CheckIsRunning()
        {
            NamedPipeClientStream clientStream = new NamedPipeClientStream(PipeName);
            try
            {
                clientStream.Connect(1000);
            }
            catch (TimeoutException)
            {
                tb.Text = $"No Server found.";
                return false;
            }

            clientStream.WriteByte((byte)EPipeCommands.Show);
            return true;
        }

        EPipeCommands InterpretePipeCommand(int v)
        {
            if (Enum.TryParse<EPipeCommands>($"{v}", out var cmd))
                return cmd;

            return EPipeCommands.None;
        }

        /// <summary> Creates the server, listens to connectiontrys, 
        /// reads 1 byte & disconnects </summary> 
        /// <param name="data"></param>
        void PipeServer(object data)
        {
            pipeServerStream = new NamedPipeServerStream(
                PipeName, PipeDirection.InOut, 
                2, PipeTransmissionMode.Byte);

            do
            {
                pipeServerStream.WaitForConnection();

                if (pipeServerStream.IsConnected && !isClosing)
                {
                    ActOnPipeCommand(
                        InterpretePipeCommand(
                            pipeServerStream.ReadByte()));
                }
                pipeServerStream.Disconnect();
            }
            while (!isClosing);
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (CheckIsRunning())
                Close();
            else
            {
                ServerThread = new Thread(PipeServer);
                ServerThread.Start();

                tb.Text = "Starting new pipe server.\n";

                Closing += (a, b) => isClosing = true;
            }
        }
    }
}

暂无
暂无

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

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