/*1. SQLite를 설치한(Install) 후에
2. SQLite DLL을 프로젝트에 참조한 후에*/

using System;
using System.Data.SQLite;

class Program
{
public static void Main()
{
SQLiteManageCls nm = new SQLiteManageCls();
nm.running();
}
}

class SQLiteManageCls
{
string connectionString = "Data Source=:memory:"; 
SQLiteConnection sqliteConnection = null; 
SQLiteCommand sqliteCommand = null;

public void running()
{
try 

sqliteConnection = new SQLiteConnection(connectionString); 
sqliteConnection.Open(); 
string sql = "SELECT SQLITE_VERSION()"; 
sqliteCommand = new SQLiteCommand(sql, sqliteConnection); 
string version = sqliteCommand.ExecuteScalar().ToString(); 
Console.WriteLine("SQLite version : {0}", version); 
}
catch(SQLiteException sqliteException) 

Console.WriteLine("Error: {0}", sqliteException.ToString()); 

finally 
{
if(sqliteCommand != null) { sqliteCommand.Dispose(); }
if(sqliteConnection != null) 
{
try 

sqliteConnection.Close(); 

catch(SQLiteException sqliteException) 

Console.WriteLine("Closing connection failed."); 
Console.WriteLine("Error: {0}", sqliteException.ToString()); 

finally 

sqliteConnection.Dispose(); 
}
}
}
}
}

using System;  
using System.Collections.Generic;  
using System.Net;  
using System.Net.Sockets;  
using System.IO;  
using System.Text;  
 
namespace FileTransfer  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            // Listen on port 31234    
            TcpListener tcpListener = new TcpListener(IPAddress.Any, 31234);  
            tcpListener.Start();  
 
            Console.WriteLine("Server started");  
 
            //Infinite loop to connect to new clients    
            while (true)  
            {  
                // Accept a TcpClient    
                TcpClient tcpClient = tcpListener.AcceptTcpClient();  
 
                Console.WriteLine("Connected to client");  
 
                StreamReader reader = new StreamReader(tcpClient.GetStream());  
 
                // The first message from the client is the file size    
                string cmdFileSize = reader.ReadLine();  
 
                // The first message from the client is the filename    
                string cmdFileName = reader.ReadLine() + "_1";  
 
                int length = Convert.ToInt32(cmdFileSize);  
                byte[] buffer = new byte[length];  
                int received = 0;  
                int read = 0;  
                int size = 1024;  
                int remaining = 0;  
 
                // Read bytes from the client using the length sent from the client    
                while (received < length)  
                {  
                    remaining = length - received;  
                    if (remaining < size)  
                    {  
                        size = remaining;  
                    }  
 
                    read = tcpClient.GetStream().Read(buffer, received, size);  
                    received += read;  
                }  
 
                // Save the file using the filename sent by the client    
                using (FileStream fStream = new FileStream(Path.GetFileName(cmdFileName), FileMode.Create))  
                {  
                    fStream.Write(buffer, 0, buffer.Length);  
                    fStream.Flush();  
                    fStream.Close();  
                }  
 
                Console.WriteLine("File received and saved in " + Environment.CurrentDirectory);  
            }  
        }  
    }  

using System;  
using System.Collections.Generic;  
using System.Net;  
using System.Net.Sockets;  
using System.IO;  
using System.Text;  
 
namespace FileTransferClient  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            try  
            {  
                Console.WriteLine("Please enter a full file path");  
                string fileName = Console.ReadLine();  
 
                TcpClient tcpClient = new TcpClient("127.0.0.1", 31234);  
                Console.WriteLine("Connected. Sending file.");  
 
                StreamWriter sWriter = new StreamWriter(tcpClient.GetStream());  
 
                byte[] bytes = File.ReadAllBytes(fileName);  
 
                sWriter.WriteLine(bytes.Length.ToString());  
                sWriter.Flush();  
 
                sWriter.WriteLine(fileName);  
                sWriter.Flush();  
 
                Console.WriteLine("Sending file");  
                tcpClient.Client.SendFile(fileName);  
 
            }  
            catch (Exception e)  
            {  
                Console.Write(e.Message);  
            }  
 
            Console.Read();  
        }  
    }  

 

Other Application기동을 클라이언트에서 하도록 수정(Other Application프로그램이 뛰워져 있지 않을경우에)
Other Application기동을 클라이언트에서 하도록 수정(Other Application프로그램이 뛰워져 있지 않을경우에)

____handle_mmm = FindWindow(null, "CONSOLE.TRIS");
if(____handle_mmm==IntPtr.Zero)
{
Console.WriteLine("Time:[" + DateTime.Now.ToString() + "]::" + "FindWindow(CONSOLE.TRIS) FAIL!!, Try Execute CONSOLE.TRIS Application!!");

Process process = Process.Start("____rcv.exe");

DateTime endTime = DateTime.Now.AddMinutes(1);

/*
System.Threading.Thread.Sleep(1000);
____handle_mmm = FindWindow(null, "CONSOLE.TRIS");
if(____handle_mmm==IntPtr.Zero) 
{
Console.WriteLine("Time:[" + DateTime.Now.ToString() + "]::" + "FindWindow(CONSOLE.TRIS) FAIL!!, Try Execute CONSOLE.TRIS Application!!");
}
*/

while(true)
{
if((____handle_mmm = FindWindow(null, "CONSOLE.TRIS"))==IntPtr.Zero)
{
System.Threading.Thread.Sleep(10);
}
else break;

if(endTime<DateTime.Now)
{
index=100;
break;
}
}
if(index==100) return;
}

 

 

____snd.cs
0.00MB

/*2개의 Application이 동작한다. 2개의 Application이 Data를 Communication할때에 사용하는 방식이다.
1. Console에서 Key를 동작하여, 다른 Application으로 SendMessage(Text)한다. 일명 조정
2. 다른 Application에서는 WndProc(override frm)에서 WM_COPYDATA를 통해서 데이타를 받은다음에 
Key에 따라서 동작한다.
3. 억지로 말을 붙이자면, 한쪽방향으로의 클라이언트,서버의 관계이다.*/

>주의할점은 Tris Server Frm(No Key) 의 Application의 Handle이 반드시 일단 존재해야 한다.

____snd.cs
0.00MB

 

____rcv.cs
0.01MB

 

/*Data communication between Proesses!!*/

Windows OS
프로세스간 Window Handle 공유를 통한 SendMessage & WndProc(WM_COPYDATA)

참조)
SendMessage/FindWindow/Snd/Rcv Str :: 석수코딩교육 (tistory.com)

Linux & Unix OS
1) 프로세스간 Message Queue 공유를 통한 Message Send & Recv
2) 프로세스간 Semaphor & Shared Meory 공유를 통한 Message Send & Recv(비추)

1) 핸들을 알았을떄에, 해당frm에 메세지보내기
2) 핸들은 모르지만, 타이틀을 알았을때에 해당frm에 메세지보내기

using NoName;
using NoName.Text;//Encoding
using NoName.ComponentModel;//BackgroundWorker
using NoName.Timers;
using NoName.Windows.Forms;
using NoName.Runtime.InteropServices;

class MessageHandleCls
{
public int WM_COPYDATA=0x004A;
/*--------------------------------------------------------------------------------------------------*/
[DllImport("user32.dll", CharSet=CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, int unMsg, IntPtr wParam, IntPtr lParam);

[DllImport("user32.dll", CharSet=CharSet.Auto)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
/*--------------------------------------------------------------------------------------------------*/

IntPtr ____handle;

public struct COPYDATASTRUCT
{
public IntPtr dwData;
public int cbData;
public IntPtr lpData;
}

NoName.Timers.Timer tm = new NoName.Timers.Timer();
NoName.Timers.Timer tmmmm = new NoName.Timers.Timer();
Random rr = new Random();

public void running(IntPtr ____hwnd)
{
____handle=____hwnd;

tm.Elapsed += new ElapsedEventHandler(____time_tick);
tm.Interval = 1000;
tm.Start();

tmmmm.Elapsed += new ElapsedEventHandler(____time_tick_mmm);
tmmmm.Interval = 1000;
tmmmm.Start();
}
void ____time_tick(object sender, ElapsedEventArgs e)
{
int index=0;
int xpos;
string formatText="";

xpos = rr.Next() % 5;

if(xpos % 5 == 0) formatText="RIGHT";
else if(xpos % 5 == 1) formatText="LEFT";
else if(xpos % 5 == 2) formatText="DOWN";
else if(xpos % 5 == 3) formatText="RETURN";
else if(xpos % 5 == 4) formatText="SPACE";

byte[] dataByte=Encoding.UTF8.GetBytes(formatText);

COPYDATASTRUCT cpyData=new COPYDATASTRUCT();
cpyData.dwData=(IntPtr)0;
cpyData.cbData=formatText.Length;
cpyData.lpData=Marshal.AllocHGlobal(dataByte.Length);
Marshal.Copy(dataByte,0,cpyData.lpData,dataByte.Length);

IntPtr sndData=Marshal.AllocHGlobal(Marshal.SizeOf(cpyData));
Marshal.StructureToPtr(cpyData,sndData,true);

Console.WriteLine("Time:[" + DateTime.Now.ToString() + "]::" + ">>>>>>>>>>>SendStr:[" + sndData + "]");

IntPtr ____result=SendMessage(____handle, WM_COPYDATA, (IntPtr)index, sndData);

Marshal.FreeHGlobal(cpyData.lpData);
Marshal.FreeHGlobal(sndData);
}
void ____time_tick_mmm(object sender, ElapsedEventArgs e)
{
int index=0;
int xpos;
string formatText="";
IntPtr ____handle_mmm;

____handle_mmm = FindWindow(null, "DEBUGGING");

xpos = rr.Next() % 5;

if(xpos % 5 == 0) formatText="RIGHT";
else if(xpos % 5 == 1) formatText="LEFT";
else if(xpos % 5 == 2) formatText="DOWN";
else if(xpos % 5 == 3) formatText="RETURN";
else if(xpos % 5 == 4) formatText="SPACE";

byte[] dataByte=Encoding.UTF8.GetBytes(formatText);

COPYDATASTRUCT cpyData=new COPYDATASTRUCT();
cpyData.dwData=(IntPtr)0;
cpyData.cbData=formatText.Length;
cpyData.lpData=Marshal.AllocHGlobal(dataByte.Length);
Marshal.Copy(dataByte,0,cpyData.lpData,dataByte.Length);

IntPtr sndData=Marshal.AllocHGlobal(Marshal.SizeOf(cpyData));
Marshal.StructureToPtr(cpyData,sndData,true);

Console.WriteLine("Time:[" + DateTime.Now.ToString() + "]::" + ">>>>>>>>>>>SendStrTmp:[" + sndData + "]");

IntPtr ____result=SendMessage(____handle_mmm, WM_COPYDATA, (IntPtr)index, sndData);

Marshal.FreeHGlobal(cpyData.lpData);
Marshal.FreeHGlobal(sndData);
}
}

class WindowsManageCls : Form
{
const int WM_COPYDATA=0x004A;

public struct COPYDATASTRUCT
{
public IntPtr dwData;
public int cbData;
public IntPtr lpData;
}


MessageHandleCls nm = new MessageHandleCls();

public WindowsManageCls()
{
this.Text = "DEBUGGING";

nm.running(this.Handle);
}

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
const int WM_KEYDOWN = 0x0100, WM_SYSKEYDOWN = 0x0104;

if ((msg.Msg == WM_KEYDOWN) || (msg.Msg == WM_SYSKEYDOWN))
{
         switch (keyData.ToString())
         {
case "Return" :
DialogResult dialogResult = MessageBox.Show("Quit OK!!", "Inform",
              MessageBoxButtons.OKCancel, MessageBoxIcon.Information);

if (dialogResult == DialogResult.OK) Application.Exit();
break;
case "Right"  :
break;
case "Left"   :
break;
         default:
             break;
         }
     }
return base.ProcessCmdKey(ref msg, keyData);
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);

try
{
switch(m.Msg)
{
case WM_COPYDATA :
COPYDATASTRUCT cds=(COPYDATASTRUCT)m.GetLParam(typeof(COPYDATASTRUCT));
byte[] rcvData=new byte[cds.cbData];
Marshal.Copy(cds.lpData,rcvData,0,cds.cbData);
String strText=Encoding.UTF8.GetString(rcvData);
Console.WriteLine("Time:[" + DateTime.Now.ToString() + "]::" + "ReceiveStr:[" + strText + "]");
break;
default:
break;
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}

class Program
{
public static void Main(string[] args)
{
Application.Run(new WindowsManageCls());
}
}






ex40.cs
0.01MB

//NoName->System 으로 변경//NoName->System 으로 변경//NoName->System 으로 변경//NoName->System 으로 변경//NoName->System 으로 변경
using NoName; 
using NoName.ComponentModel;
using NoName.Windows.Forms;
using NoName.Drawing;
using NoName.Drawing.Drawing2D;
using NoName.Timers;

class Program
{
public static void Main(string[] args)
{
//Application.EnableVisualStyles();
//Application.SetCompatibleTextRenderingDefault(false);


if(args.Length==1) 
{
if(args[0]=="E") Application.Run(new OtherManageCls());
}
}
}

class OtherManageCls : Form
{
int ____hatchstyle=0;
const int WM_KEYDOWN = 0x0100, WM_KEYUP = 0x0101, WM_CHAR = 0x0102, WM_SYSKEYDOWN = 0x0104, WM_SYSKEYUP = 0x0105, WM_PAINT = 0x000f, WM_SIZE = 0x0005;

public OtherManageCls()
{
this.Width = 700;
this.Height = 300;
}
void draw()
{
int xx,yy,width,height;

xx = this.Width / 4;
yy = this.Height / 4;
width = this.Width / 4 * 2;
height = this.Height / 4;

DrawBackground(0,0,this.Width,this.Height,____hatchstyle);
DrawForeground(xx,yy,width,height,____hatchstyle);

this.Text = "Time:[" + DateTime.Now.ToString() + "]" + ">>HatchStyle Number:[" + ____hatchstyle.ToString("00") + "]";
}
void DrawForeground(int xx, int yy, int width, int height, int ____hatchstyle)
{
HatchStyle hs = (HatchStyle)____hatchstyle;
Brush myBrush = new HatchBrush(hs, NoName.Drawing.Color.SteelBlue);
Pen myPen = new Pen(NoName.Drawing.Color.LightGray, 1);

NoName.Drawing.Graphics formGraphics;
formGraphics = this.CreateGraphics();
formGraphics.FillRectangle(myBrush, new Rectangle(xx, yy, width, height));
formGraphics.DrawRectangle(myPen , xx, yy, width, height);
}
void DrawBackground(int xx, int yy, int width, int height, int ____hatchstyle)
{
HatchStyle hs = (HatchStyle)____hatchstyle;
Brush myBrush = new HatchBrush(hs, NoName.Drawing.Color.LightYellow);
Pen myPen = new Pen(NoName.Drawing.Color.LightGray, 1);

NoName.Drawing.Graphics formGraphics;
formGraphics = this.CreateGraphics();
formGraphics.FillRectangle(myBrush, new Rectangle(xx, yy, width, height));
formGraphics.DrawRectangle(myPen , xx, yy, width, height);
}

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if ((msg.Msg == WM_KEYDOWN) || (msg.Msg == WM_SYSKEYDOWN))
{
switch (keyData.ToString())
{
case "Return" :
DialogResult dialogResult = MessageBox.Show("Quit OK!!", "Inform",
MessageBoxButtons.OKCancel, MessageBoxIcon.Information);

if (dialogResult == DialogResult.OK) Application.Exit();
break;
case "Right"  :
____hatchstyle += 1;
if(____hatchstyle == 53) ____hatchstyle=0;
break;
case "Left"   :
____hatchstyle -= 1;
if(____hatchstyle == -1) ____hatchstyle=52;
break;
default:
break;
}

draw();
}
return base.ProcessCmdKey(ref msg, keyData);
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);

try
{
switch(m.Msg)
{
case WM_PAINT :
draw();
break;
default:
break;
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}

'c# 언어 > 중급과정' 카테고리의 다른 글

Data communication between Proesses!!  (0) 2022.03.25
SendMessage/FindWindow/Snd/Rcv Str  (0) 2022.03.15
HatchStyle,HatchBrush,Pen  (0) 2022.03.08
Hexa 4가지 항목으로 점수계산 로직  (0) 2022.03.06
LINQ 쿼리 소개(C#)  (0) 2022.02.23

+ Recent posts