将字符串从wpf应用程序传递到winforms应用程序

时间:2014-11-30 11:45:40

标签: wpf string winforms

我有一个用C#编写的现有CAD WinForms宏来管理文件操作(一些小的过滤)。然而,我在WPF中开发了用于文件存储和项目管理的PLM工具,允许我通过标签过滤记录,并按准确度排序。

我想: 1.在我的winforms宏中打开WPF应用程序 2.从表示文件路径的WPF应用程序中接收一个字符串

如果不使用中间文件,你会如何推荐关于第2点?

1 个答案:

答案 0 :(得分:0)

您可以使用IPC打开可用于跨进程通信的通道。这是一个准确的实现,应该很容易适应您的目的:

服务器

void Main()
{
    StringWriter writer = null;
    IChannel serverChannel = null;

    try
    {
        serverChannel = new IpcChannel("localhost:9090");
        ChannelServices.RegisterChannel(serverChannel, true);
        RemotingConfiguration.RegisterWellKnownServiceType(typeof(StringWriter), "Writer.rem", WellKnownObjectMode.Singleton);
    }
    catch(RemotingException ex)
    {
        ex.Dump();
    }

    writer = (StringWriter)Activator.GetObject(typeof(StringWriter), "ipc://localhost:9090/Writer.rem");
    var quit = false;

    while(!quit)
    {
        var task = Task.Factory.StartNew(() =>
            {
                Console.ReadLine();
                quit = true;
            });
        task.Wait(1000);
        var builder = writer.GetStringBuilder();
        if (builder.Length > 0)
        {
            builder.ToString().Dump();
            break;
        }
    }

    writer.Dispose();
    ChannelServices.UnregisterChannel(serverChannel);
    "Server shutdown.".Dump();
}

Download in LinqPad

<强>客户端

void Main()
{
    try
    {
        var client = new BinaryClientFormatterSinkProvider();
        var server = new BinaryServerFormatterSinkProvider();
        server.TypeFilterLevel = TypeFilterLevel.Full;

        Hashtable config = new Hashtable();
        config["name"] = "localhost:9090";
        config["typeFilterLevel"] = "Full";
        config["impersonate"] = "false";
        config["tokenImpersonationLevel"] = "Impersonation";
        config["useDefaultCredentials"] = "True";
        config["secure"] = "True";

        var channel = new IpcChannel(config, client, server);
        ChannelServices.RegisterChannel(channel);

        var remoteType = new WellKnownClientTypeEntry(typeof(StringWriter), "ipc://localhost:9090/Writer.rem");

        RemotingConfiguration.RegisterWellKnownClientType(remoteType);
        string objectUri;
        var messageSink = channel.CreateMessageSink("ipc://localhost:9090/Writer.rem", null, out objectUri);

        Console.WriteLine("The URI of the message sink is {0}.", objectUri);

        if (messageSink != null)
        {
            Console.WriteLine("The type of the message sink is {0}.", messageSink.GetType().ToString());
        }
    }
    catch(RemotingException)
    {
    }

    var writer = (StringWriter)Activator.GetObject(typeof(StringWriter), "ipc://localhost:9090/Writer.rem");
    writer.WriteLine("Hello from client!");
}

Download in LinqPad