简单的匿名管道使用
匿名管道发送端代码片段:
using System.Runtime.InteropServices;
<span style="white-space:pre"> </span> using System.Diagnostics;
<pre name="code" class="csharp"><span> </span> <span style="font-family: Arial, Helvetica, sans-serif;">using System.IO.Pipes;</span>
<span> </span> <span style="font-family: Arial, Helvetica, sans-serif;">using System.IO;</span>
<span style="white-space:pre"> </span> Process process = new Process();
AnonymousPipeServerStream pipeStream = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable);
StreamWriter sw;
private void SetUpCBTHook()
{
try
{
process.StartInfo.FileName = "run32hook.exe";
//将句柄传递给子进程
process.StartInfo.Arguments = pipeStream.GetClientHandleAsString();
process.StartInfo.UseShellExecute = false;
process.Start();
//创建匿名管道流实例
sw = new StreamWriter(pipeStream);
//销毁子进程的客户端句柄?
pipeStream.DisposeLocalCopyOfClientHandle();
sw.AutoFlush = true;
//System.Diagnostics.Process.Start("run32hook.exe");
sw.WriteLine("starthook");
}
catch (Exception ex)
{
}
}
匿名管道接收端代码:
program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Pipes;
using System.IO;
using System.Runtime.InteropServices;
namespace run32hook
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
[DllImport("winhook.dll")]
static extern int setHookDll();
[DllImport("winhook.dll")]
static extern bool unHookDll();
static void Main(string[] args)
{
string strPipeHandle = args[0];
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 frm = new Form1();
frm.Text = strPipeHandle;
//Application.Run(frm);
//setHookDll();
AnonymousPipeClientStream pipeStream = new AnonymousPipeClientStream(PipeDirection.In, strPipeHandle);
StreamReader sr = new StreamReader(pipeStream);
string line;
while (true)
{
if ((line = sr.ReadLine()) != null)
{
switch (line)
{
case "starthook":
break;
case "unhook":
break;
case "exit":
return;
default:
Console.WriteLine("default: {0}", line);
break;
}
}
}
}
}
}