Winform应用程序在控制台中写入其消息

时间:2013-06-27 10:40:25

标签: winforms c#-4.0 console-application

我在这里有两个提案..我有一个运行的Windows应用程序。 第一个建议是我应该将消息直接写入控制台(命令提示符),即使它不是控制台应用程序。

第二个选项是我应该创建一个控制台应用程序,在该应用程序中它应该读取windows应用程序生成的日志文件并将其写入控制台。请注意,Windows应用程序将在运行时实时更新日志文件,我希望控制台应用程序在下一刻自己读取日志中的每条更新消息。这有可能吗?

哪个可行?以及我如何实现这一目标?

非常感谢快速回复.. 感谢...

1 个答案:

答案 0 :(得分:1)

第三种方法 - 使用进程间通信从控制台应用程序中监听winforms应用程序事件。例如,您可以使用.NET Remoting,WCF或MSMQ。

因此,您需要从Windows窗体应用程序中编写日志,并在控制台应用程序中接收相同的数据,然后您可以利用NLog日志记录框架,它可以编写日志both to files and MSMQ。从Nuget.0获取 NLog.dll NLog.Extended.dll NLog.config 文件中配置两个目标:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

 <targets>
    <target xsi:type="MSMQ" name="msmq" queue=".\private$\CoolQueue"
         useXmlEncoding="true" recoverable="true" createQueueIfNotExists="true"
         layout="${longdate}|${level:uppercase=true}|${logger}|${message}"/>
    <target xsi:type="File" name="file" fileName="logs/${shortdate}.log"
         layout="${longdate} ${uppercase:${level}} ${message}" />
  </targets>
  <rules>
    <logger name="*" minlevel="Trace" writeTo="msmq" />
    <logger name="*" minlevel="Trace" writeTo="file" />
  </rules>
</nlog>

然后在winforms应用程序中获取记录器

private static Logger _logger = LogManager.GetCurrentClassLogger();

并使用它来编写日志消息:

private void button1_Click(object sender, EventArgs e)
{
    _logger.Debug("Click");
}

现在转到控制台应用程序。您需要读取由winforms应用程序发布的MSMQ队列中的消息。创建队列并开始监听:

string path = @".\private$\CoolQueue";

MessageQueue queue = MessageQueue.Exists(path) ?
    new MessageQueue(path) :
    MessageQueue.Create(path);

queue.Formatter = new XmlMessageFormatter(new[] { typeof(string) });
queue.ReceiveCompleted += ReceiveCompleted;
queue.BeginReceive();

收到消息后将消息写入控制台:

static void ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
{        
    Console.WriteLine(e.Message.message.Body);
    var queue = (MessageQueue)sender;
    queue.BeginReceive();
}

如果您想使用远程处理,请查看Building a Basic .NET Remoting Application文章。

相关问题