티스토리 뷰

반응형

[wpf/winform/c#/unity]  serial / udp 받아서 키보드 이벤트 발생(hooking) 풀코드 제공

 

#serial - 이벤트 방식 receive

#udp - 이벤트 방식 receive

#키보드 훅 싱글톤 함수 

(출저: https://rito15.github.io/posts/cs-global-key-hook/)

 

 

 public class SerialHelper
    {
        private static SerialHelper _instance { get; set; }
        public static SerialHelper Instance
        {
            get
            {
                return _instance ?? (_instance = new SerialHelper());
            }
        }

        SerialPort serial;

        public delegate void PacketReceiveEventHandler(string code);
        public event PacketReceiveEventHandler PacketReceiveEventHandlerEvent;

        public SerialHelper()
        {
            Init();
        }

        BackgroundWorker bg;

        private void Init()
        {
            serial = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
            serial.DataReceived += Serial_DataReceived;
            bg = new BackgroundWorker();
            bg.DoWork += Bg_DoWork;

        }

        private void Serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            Debug.WriteLine(e);
            PacketReceiveEventHandlerEvent(e.ToString());
        }

        public void Start()
        {
            bg.RunWorkerAsync();
        }

        public void Stop()
        {
            bg.CancelAsync();
            Disconnect();
        }

        private void Bg_DoWork(object sender, DoWorkEventArgs e)
        {
            Connect();
        }

        private void Connect()
        {
            serial.Open();
            
        }

        private void Disconnect()
        {
            serial.Close();
        }
    }

 

#serial - 이벤트 방식 receive

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Loaded += MainWindow_Loaded;
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            InitializeNetwork();
        }

        public void InitializeNetwork()
        {
            UdpHelper.Instance.PacketReceiveEventHandlerEvent += Instance_PacketReceiveEventHandlerEvent_UDP;
            UdpHelper.Instance.Start(11116);

            SerialHelper.Instance.PacketReceiveEventHandlerEvent += Instance_PacketReceiveEventHandlerEvent;
            SerialHelper.Instance.Start();
        }

        #region Events
        private void Instance_PacketReceiveEventHandlerEvent_UDP(string code)
        {
            switch (code)
            {
                case "Hello":
                    hooksHelper.Instance.ForceKeyPress(System.Windows.Forms.Keys.D1);
                    break;
                default:
                    break;
            }
        }

        private void Instance_PacketReceiveEventHandlerEvent(string code)
        {
            switch (code)
            {
                case "Hello":
                    hooksHelper.Instance.ForceKeyPress(System.Windows.Forms.Keys.D1);
                    break;
                default:
                    break;
            }
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            base.OnKeyDown(e);
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            SerialHelper.Instance.Stop();
            base.OnClosing(e);
        } 
        #endregion
    }

 

#udp - 이벤트 방식 receive

 public class UdpHelper
    {
        public string server_host = "192.168.0.168";
        public string server_broadcast = "255.255.255.255";
        public int receiver_port = 2222;
        public int sender_port = 1111;

        private UdpClient sender;
        private UdpClient receiver;
        private static UdpHelper _instance { get; set; }
        public static UdpHelper Instance
        {
            get
            {
                return _instance ?? (_instance = new UdpHelper());
            }
        }

        public void Start(int receiver_port)
        {
            this.receiver_port = receiver_port;
            Receive();
        }

        public delegate void PacketReceiveEventHandler(string code);

        public void Receive(object rECEIVER_PORT)
        {
            throw new NotImplementedException();
        }

        public event PacketReceiveEventHandler PacketReceiveEventHandlerEvent;

        UdpHelper()
        {

        }

        public void Send(string msg)
        {
            Send(msg, false);
        }

        public void Send(string msg, int port)
        {
            Send(msg, false, port);
        }

        public void Send(string msg, bool isBroadCast)
        {
            Send(msg, isBroadCast, sender_port);
        }

        public void Send(string ip,string msg, int port)
        {
            server_host = ip;
            sender_port = port;
            Send(msg);
        }

        public async void Send(string msg, bool isBroadCast, int port)
        {
            try
            {

                sender = new UdpClient(isBroadCast ? server_broadcast : server_host, port);
                byte[] msgToByte = DataConverter.StringToByte(msg);
                _ = await sender.SendAsync(msgToByte, msgToByte.Length);
                sender.Close();
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }
        }


        public void Receive()
        {
            Receive(receiver_port);
        }

        public async void Receive(int Port)
        {
            try
            {
                IPEndPoint epRemote = new IPEndPoint(IPAddress.Any, Port);
                receiver = new UdpClient(epRemote);
                var receive = await receiver.ReceiveAsync();
                string msg = DataConverter.ByteToString(receive.Buffer);
                Debug.WriteLine(msg);
                PacketReceiveEventHandlerEvent(msg);
                ////자신이 보낸 패킷은 무시
                //if (!NetworkHelper.IsLocalHost(receive.RemoteEndPoint))
                //{
                //    string msg = DataConverter.ByteToString(receive.Buffer);
                //    Debug.WriteLine(msg);
                //    PacketReceiveEventHandlerEvent(msg);
                //}
                receiver.Close();
                Receive();
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }
        }
    }

 

#serial #udp #hook #keyboard

 

반응형
댓글
반응형