Wednesday, 31 December 2014

C# Chat Application Over Asynchronous UDP Sockets (server and client side)

This is two article very easy written by C# a server support multi users can chat from client in a local network.

Server side:
http://www.daveoncsharp.com/2009/08/csharp-chat-application-over-asynchronous-udp-sockets-part-1/


Client side:
http://www.daveoncsharp.com/2009/08/csharp-chat-application-over-asynchronous-udp-sockets-part-2/

Friday, 19 December 2014

Single instance in c#

Today, I will share an easy way to create a single instance application in C#.

Add Microsoft.VisualBasic in references by righ click to References -> Add Reference...

Add microsoft visualbasic tientuts

Default content of Program.cs is:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

Change to:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Microsoft.VisualBasic.ApplicationServices;


namespace DesktopServer
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            string[] args = Environment.GetCommandLineArgs();
            SingleInstanceController controller = new SingleInstanceController();
            controller.Run(args);
        }
    }

    public class SingleInstanceController : WindowsFormsApplicationBase
    {
        public SingleInstanceController()
        {
            IsSingleInstance = true;
            StartupNextInstance += this_StartupNextInstance;
        }

        void this_StartupNextInstance(object sender, StartupNextInstanceEventArgs e)
        {
            Form1 form = MainForm as Form1; //My derived form type
        }

        protected override void OnCreateMainForm()
        {
            MainForm = new Form1();
        }
    }
}

Wednesday, 17 December 2014

Example using android remote desktop to control mouse via wifi

I searched an easy and helpful source code an android app connect with c# server in desktop via wifi and control mouse in desktop in here. Behind is content:

After my last post about .NET – Android, I was pretty excited about the possibilities. Therefore, I decided to create a new little “useful” app for my phone.
If your mouse batteries are low and you have to finish something, you can use your phone as a mouse.
How it works on Android:
I created an app which captures the movements on the screen and sends the positions over a socket (UDP) to my PC. My “protocol” supports following commands:
D.CLICKSending a double click. (Not really necessary.)
CLICKSending a click. (2x “click” => same as d.click.)
X,YSending delta x and y. 0,1 or 1,0 etc.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
@Override
public boolean onTouchEvent(MotionEvent event) {
    super.onTouchEvent(event);
    switch(event.getAction()) {
        case MotionEvent.ACTION_DOWN: {
            final float x = event.getX();
            final float y = event.getY();
            // last position
            this.lastX = x;
            this.lastY = y;
            // first position
            this.firstX = x;
            this.firstY = y;
            // click time
            this.clickDown = new Date();
            break;
        }
        case MotionEvent.ACTION_MOVE: {
            // new position
            final float x = event.getX();
            final float y = event.getY();
             
            //  get delta
            final float deltax = x - this.lastX;
            final float deltay = y - this.lastY;
            // set last position
            this.lastX = x;
            this.lastY = y;
                             
            try {
                // prepare message -> x,y
                byte[] message = (deltax + "," + deltay).getBytes("UTF-8");
                // package definition. ip of pc and port.
                this.packet = new DatagramPacket(message, message.length,
                        InetAddress.getByName("192.168.0.150"), 8000);
                // send package
                this.socket.send(this.packet);
            } catch(Throwable e) {
                e.printStackTrace();
            }
            break;
        }
         
        case MotionEvent.ACTION_UP: {
            // get current position
            final float x = event.getX();
            final float y = event.getY();
            // get delta
            final float deltaX = this.firstX - x;
            final float deltaY = this.firstY - y;
             
            Date now = new Date();
            byte[] message = null;
             
            try {
                // when the users clicks and holds over 1 second send a double click to the pc.
                if (deltaX < this.tolerance[0] &&
                    deltaX > this.tolerance[1] &&
                    deltaY < this.tolerance[0] &&
                    deltaY > this.tolerance[1] &&
                    now.getTime() - this.clickDown.getTime() >= 1000) {
                    message = ("d.click").getBytes("UTF-8");
                // When the users clicks (not holding) send a normal click to the pc.
                } else if (x == this.firstX && y == this.firstY) {
                    message = ("click").getBytes("UTF-8");
                }
                if (message != null) {
                    // prepare and send package -> d.click or click
                    this.packet = new DatagramPacket(message, message.length, InetAddress.getByName("192.168.0.150"), 8000);
                    this.socket.send(this.packet); 
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }
            break;
        }
    }
    return true;
}
Application on the PC:
I created an application, which receives the packages and sets the cursor position on the PC:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
public partial class MainWindow : Window
{
    // Dll import. -> method mouse_move
    [DllImport("user32.dll")]
    static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);
    private EndPoint point;
    private Socket receiveSocket;
    private byte[] recBuffer;
    private int speed = 2;
    // Flags for mouse_event api
    [Flags]
    public enum MouseEventFlagsAPI
    {
        LEFTDOWN = 0x00000002,
        LEFTUP = 0x00000004,
        MIDDLEDOWN = 0x00000020,
        MIDDLEUP = 0x00000040,
        MOVE = 0x00000001,
        ABSOLUTE = 0x00008000,
        RIGHTDOWN = 0x00000008,
        RIGHTUP = 0x00000010
    }
    public MainWindow()
    {
        InitializeComponent();
    }
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        // initilization and listening
        receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            point = new IPEndPoint(IPAddress.Any, 8000);
        this.recBuffer = new byte[60];
        receiveSocket.Bind(point);
        receiveSocket.BeginReceiveFrom(recBuffer, 0, recBuffer.Length,
            SocketFlags.None, ref point,
            new AsyncCallback(MessageReceiveCallback), (object)this);
             
    }
    private void SendClick()
    {
        // Send click to system
        mouse_event((int)MouseEventFlagsAPI.LEFTDOWN, 0, 0, 0, 0);
        mouse_event((int)MouseEventFlagsAPI.LEFTUP, 0, 0, 0, 0);
    }
    private void MessageReceiveCallback(IAsyncResult result)
    {
        EndPoint remote = new IPEndPoint(0, 0);
        string pos = "";
        try
        {
            // get received message.
            pos = Encoding.UTF8.GetString(recBuffer);
            // clicked?
            if (pos.StartsWith("click"))
                this.SendClick();
            // long click = double click
            else if (pos.StartsWith("d.click"))
            {
                this.SendClick();
                this.SendClick();
            }
            // Otherwise move
            else
            {
                // calculate delta
                int deltaX = (int)float.Parse(pos.Substring(0, pos.IndexOf(","))) * this.speed;
                int deltaY = (int)float.Parse(pos.Substring(pos.IndexOf(",") + 1,
                    pos.IndexOf("\0") + 1 - pos.IndexOf(",") + 1)) * this.speed;
                // set new point
                System.Drawing.Point pt = System.Windows.Forms.Cursor.Position;
                System.Windows.Forms.Cursor.Position = new System.Drawing.Point(pt.X + deltaX, pt.Y + deltaY);
            }
        }
        catch (Exception)
        {
            Console.Write(pos);
        }
        // End and "begin" for next package
        this.receiveSocket.EndReceiveFrom(result, ref remote);
        receiveSocket.BeginReceiveFrom(recBuffer, 0, recBuffer.Length,
            SocketFlags.None, ref point,
            new AsyncCallback(MessageReceiveCallback), (object)this);
    }
}
Watch the video! ;)
The C# source code is here
The Java source code is here