IPC (Inter Process Communication) 방식 중 네임드파이프 통신이 있습니다.
서로 다른 프로그램에서 정의된 파이프 이름만 알면 통신이 가능한 방식입니다.
아래는 결과와 소스코드!
using System;
using System.IO;
using System.IO.Pipes;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class NamedPipe : Form
{
private const string myName = "A_Pipe"; //이름만 바꿔서 사용 가능
private const string targetName = "B_Pipe"; //이름만 바꿔서 사용 가능
private bool isOpen = true;
public NamedPipe()
{
InitializeComponent();
this.FormClosing += Form1_FormClosing;
button1.Click += button1_Click;
Task.Run(() =>
{
Receive();
});
}
private void Receive()
{
while (isOpen)
{
try
{
NamedPipeServerStream namedPipeServerStream = new NamedPipeServerStream(myName, PipeDirection.InOut, 10);
namedPipeServerStream.WaitForConnection(); //데이터 받을때까지 기다립니다.
StreamReader streamReader = new StreamReader(namedPipeServerStream);
string line = streamReader.ReadLine();
AddListItem(line);
streamReader.Close();
namedPipeServerStream.Close();
}
catch (Exception ex)
{
AddListItem("Receive Error : " + ex.Message);
}
}
}
private void AddListItem(string message)
{
Invoke((MethodInvoker)delegate
{
listBox1.Items.Add(message);
});
}
private void button1_Click(object sender, EventArgs e)
{
try
{
NamedPipeClientStream namedPipeClientStream = new NamedPipeClientStream(".", targetName, PipeDirection.InOut);
namedPipeClientStream.Connect(10000); //10초
StreamWriter streamWriter = new StreamWriter(namedPipeClientStream);
streamWriter.WriteLine(textBox1.Text);
streamWriter.Flush();
streamWriter.Close();
namedPipeClientStream.Close();
}
catch (Exception ex)
{
AddListItem("Send Error : " + ex.Message);
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
isOpen = false;
}
}
}
'C# > Windows Form' 카테고리의 다른 글
[C# Windows Form] 섬네일 현재 영역만 그려주기 (Scroll, Thumbnail) (0) | 2024.11.08 |
---|---|
[C# Windows Form] GDI+ 이미지 돌리기 (돌아간 크기에 맞추어 이미지 크기 확장!) (cos, sin) (1) | 2024.06.03 |
[C# Windows Form] Invoke, InvokeRequired - (Cross Thread) (0) | 2024.05.08 |
[C# Windows Form] 둥근 버튼 만들기 (GraphicsPath) (0) | 2024.03.11 |
[C# Windows Form] 디자인 문서개요 (요소 계층 구조 표현) (0) | 2024.03.11 |