C#实现远程桌面 using System; using System.Collections.Generic; using Sys

586 0
莫路 2022-6-10 11:11:33 | 显示全部楼层 |阅读模式
C#实现远程桌面
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Drawing.Imaging;


//原理:

该程序利用socket接受服务端发送来的指令,解析出相应的操作,客户端根据指令调用对应的方法。

该程序适用于初学者项目参考,其实时运行效率有待考证。


namespace TestOnLine
{
   
    public partial class 软帝考试系统 : Form
    {
        Graphics g;
        Bitmap bmp;
        Graphics g2;
        Bitmap bmp2;
       string pro = "{0}&{1}&{2}&{3}&{4}";//我的软件的协传输议
       string userName = Dns.GetHostName();// 获取我的主机名
       IPAddress ip;//我的ip
       IPAddress firedIp;//教师端的ip
       int port = 9305;//我的端口号
       public void UdpSendMessage(IPAddress sendIp, string cmdNo, string msg)
       {
           Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
           //发送的内容
           string context = string.Format(pro, userName, ip, DateTime.Now.Ticks, cmdNo, msg);
           byte[] buffer = Encoding.Default.GetBytes(context);
           //指定发给谁
           client.Connect(sendIp, port);
           //发送
           client.Send(buffer);
           //关闭
           client.Close();
       }
       public void SendData()
       {
           IPAddress ip = firedIp;//
           Socket server = new Socket(AddressFamily.InterNetwork,
           SocketType.Dgram, ProtocolType.Udp);
           server.Connect(ip, port);
           //server.SendBufferSize = 200000;  //对udp协议没用
           Rectangle rec1=new Rectangle (0,0,bmp.Width,bmp.Height);
           Rectangle rec2=new Rectangle (0,0,bmp2.Width,bmp2.Height);
           while (true)
           {


               //1


               g.Clear(Color.White);
               g.CopyFromScreen(0, 0, 0, 0, new Size(bmp.Width, bmp.Height));


               g2.Clear(Color.White);
              
               g2.DrawImage(bmp,rec2,rec1,GraphicsUnit.Pixel);
            
               //2
               //内存流,在内存中存在的流,不依赖于磁盘文件
               MemoryStream ms = new MemoryStream();
               bmp2.Save(ms, ImageFormat.Jpeg);
               //将ms流中的所有内容拿出来
               byte[] buffer = ms.GetBuffer();//得到这个流中的所有字节
               int sendLen = 60000;
               int times = buffer.Length / sendLen;
               if (buffer.Length % sendLen != 0)
               {
                   times++;
               }
               for (int i = 0; i < times - 1; i++)
               {
                   server.Send(buffer,
                       i * sendLen, sendLen, SocketFlags.None);
               }
               server.Send(buffer, (times - 1) * sendLen,
                   buffer.Length - (times - 1) * sendLen, SocketFlags.None);
               byte[] buf2 = new byte[1];//作为结束的标识
               buf2[0] = 100;
               server.Send(buf2);


           }


       }
       public void UdpRecviceMessage()
       {
           Socket server = new Socket(AddressFamily.InterNetwork,
               SocketType.Dgram, ProtocolType.Udp);
           IPAddress recId = IPAddress.Any;
           EndPoint ep = new IPEndPoint(recId, port);
           server.Bind(ep);


           byte[] buffer = new byte[65535];
           while (true)
           {
               int len = server.Receive(buffer);
               //将内容变为字符串
               string msg = Encoding.Default.GetString(buffer, 0, len);
            
               //解析这个字符串 毛主席:192.168.0.111:12122:9:炸
               string[] arr = msg.Split('&');
               string fName = arr[0];
               string fIp = arr[1];
               DateTime fDt = new DateTime(Convert.ToInt64(arr[2])); //DateTime.Parse(arr[2]);//2001-1-1
               string cmd = arr[3];
               string context = arr[4];
              
               if (cmd=="1")//控制客户端,运行本程序,最大化,挂起系统热键
               {
                   this.FormBorderStyle = FormBorderStyle.None;
                   this.WindowState = FormWindowState.Maximized;
                   Hook_Start();//禁止常用的功能键
                   firedIp = IPAddress.Parse(fIp);
                   //发送
                   Thread th = new Thread(new ThreadStart(SendData));
                   th.IsBackground = true;
                   th.Start();
               }
               if (cmd=="2")//
               {
                   this.WindowState = FormWindowState.Minimized;
                   Hook_Clear();
               }
           }
       }
        public 软帝考试系统()
        {
            InitializeComponent();
            Form.CheckForIllegalCrossThreadCalls = false;
            
            Rectangle rec = Screen.PrimaryScreen.Bounds;
            bmp = new Bitmap(rec.Width, rec.Height);
            g = Graphics.FromImage(bmp);
            bmp2 = new Bitmap(200, 150);
            g2 = Graphics.FromImage(bmp2);
           
        }
   
          //[DllImport("WinLockDll.dll",CallingConvention=CallingConvention.StdCall)]
         
        //DLL_EXP_IMP int WINAPI Desktop_Show_Hide(BOOL bShowHide)
        //public static extern int CtrlAltDel_Enable_Disable(bool bEnableDisable);
        private void button1_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }


        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {


        }
        #region 屏蔽键盘第一步:声明API
        //设置钩子
        [DllImport("user32.dll")]
        public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        //抽掉钩子
        public static extern bool UnhookWindowsHookEx(int idHook);
        [DllImport("user32.dll")]
        //调用下一个钩子
        public static extern int CallNextHookEx(int idHook, int nCode, int wParam, IntPtr lParam);


        [DllImport("kernel32.dll")]
        public static extern int GetCurrentThreadId();


        [DllImport("kernel32.dll")]
        public static extern IntPtr GetModuleHandle(string name);
        #endregion


        #region 屏蔽键盘第二步: 定义委托
        public delegate int HookProc(int nCode, int wParam, IntPtr lParam);
        static int hHook = 0;
        public const int WH_KEYBOARD_LL = 13;


        //LowLevel键盘截获,如果是WH_KEYBOARD=2,并不能对系统键盘截取,Acrobat Reader会在你截取之前获得键盘。
        HookProc KeyBoardHookProcedure;
        FileStream MyFs;//用流来屏蔽ctrl+alt+del


        //键盘Hook结构函数
        [StructLayout(LayoutKind.Sequential)]
        public class KeyBoardHookStruct
        {
            public int vkCode;
            public int scanCode;
            public int flags;
            public int time;
            public int dwExtraInfo;
        }
        #endregion


        #region 屏蔽键盘第三步:编写钩子子程
        //钩子要做的事,你要处理什么?
        public static int KeyBoardHookProc(int nCode, int wParam, IntPtr lParam)
        {
            if (nCode >= 0)
            {
                KeyBoardHookStruct kbh = (KeyBoardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyBoardHookStruct));
                if (kbh.vkCode == 91) // 截获左win(开始菜单键)
                {
                    return 1;
                }
                if (kbh.vkCode == 92)// 截获右win
                {
                    return 1;
                }
                if (kbh.vkCode == (int)Keys.Escape && (int)Control.ModifierKeys == (int)Keys.Control) //截获Ctrl+Esc
                {
                    return 1;
                }
                if (kbh.vkCode == (int)Keys.F4 && (int)Control.ModifierKeys == (int)Keys.Alt) //截获alt+f4
                {
                    return 1;
                }
                if (kbh.vkCode == (int)Keys.Tab && (int)Control.ModifierKeys == (int)Keys.Alt) //截获alt+tab
                {
                    return 1;
                }
                if (kbh.vkCode == (int)Keys.Escape && (int)Control.ModifierKeys == (int)Keys.Alt)//截获alt+esc
                {
                    return 1;
                }
                if (kbh.vkCode == (int)Keys.Escape && (int)Control.ModifierKeys == (int)Keys.Control + (int)Keys.Shift) //截获Ctrl+Shift+Esc
                {
                    return 1;
                }
                if (kbh.vkCode == (int)Keys.Space && (int)Control.ModifierKeys == (int)Keys.Alt) //截获alt+空格
                {
                    return 1;
                }
                if (kbh.vkCode == 241) //截获F1
                {
                    return 1;
                }


                //if (kbh.vkCode == (int)Keys.Space && (int)Control.ModifierKeys == (int)Keys.Control + (int)Keys.Alt) //截获Ctrl+Alt+空格
                //{
                // return 1;
                //}
            }
            return CallNextHookEx(hHook, nCode, wParam, lParam);
        }
        #endregion


        #region 屏蔽键盘第四步:调用的方法
        //打开钩子 ,并用流屏蔽任务管理器
        public void Hook_Start()
        {
            // 安装键盘钩子
            if (hHook == 0)
            {
                KeyBoardHookProcedure = new HookProc(KeyBoardHookProc);


                hHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyBoardHookProcedure,
                 GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName), 0);


                //如果设置钩子失败.
                if (hHook == 0)
                {
                    Hook_Clear();
                    //throw new Exception("设置Hook失败!");
                }
                //MyFs = new FileStream(Environment.ExpandEnvironmentVariables("%windir%\\system32\\taskmgr.exe"), FileMode.Open);
                //byte[] MyByte = new byte[(int)MyFs.Length];
                //MyFs.Write(MyByte, 0, (int)MyFs.Length);
            }
        }
        //PS:也可以通过将[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\System]
        //下的DisableTaskmgr项的值设为"1”来屏蔽任务管理器。


        //取消钩子事件 ,并关闭流,取消对任务管理器的屏蔽
        public void Hook_Clear()
        {
            bool retKeyboard = true;
            if (hHook != 0)
            {
                retKeyboard = UnhookWindowsHookEx(hHook);
                hHook = 0;
            }
            //if (null != MyFs)
            //{
            //    MyFs.Close();
            //}
            //如果去掉钩子失败.
            if (!retKeyboard) throw new Exception("UnhookWindowsHookEx failed.");
        }
        #endregion


        #region 禁用ctrl+alt+del,和其它
        //直接使用即可
        //禁用ctrl+alt+del
        //[DllImport("WinLockDll.dll", CallingConvention = CallingConvention.StdCall)]
        //public static extern int CtrlAltDel_Enable_Disable(bool bEnableDisable);


        禁止使用任务管理器
        //[DllImport("WinLockDll.dll", CallingConvention = CallingConvention.StdCall)]
        //public static extern int TaskManager_Enable_Disable(bool bEnableDisable);
        隐藏开始按钮
        //[DllImport("WinLockDll.dll", CallingConvention = CallingConvention.StdCall)]
        //public static extern int StartButton_Show_Hide(bool bShowHide);


        隐藏桌面
        //[DllImport("WinLockDll.dll", CallingConvention = CallingConvention.StdCall)]
        //public static extern int Desktop_Show_Hide(bool bShowHide);


        隐藏任务栏
        //[DllImport("WinLockDll.dll", CallingConvention = CallingConvention.StdCall)]
        //public static extern int Taskbar_Show_Hide(bool bShowHide);


        隐藏任务栏的系统时间
        //[DllImport("WinLockDll.dll", CallingConvention = CallingConvention.StdCall)]
        //public static extern int Clock_Show_Hide(bool bShowHide);


        禁止切换任务
        //[DllImport("WinLockDll.dll", CallingConvention = CallingConvention.StdCall)]
        //public static extern int TaskSwitching_Enable_Disable(bool bEnableDisable);


        //[DllImport("WinLockDll.dll", CallingConvention = CallingConvention.StdCall)]
        //public static extern int Keys_Enable_Disable(bool bEnableDisable);
        //DLL_EXP_IMP int WINAPI Keys_Enable_Disable(bool bEnableDisable);
        //DLL_EXP_IMP int WINAPI AltTab1_Enable_Disable(bool bEnableDisable);
        //DLL_EXP_IMP int WINAPI AltTab2_Enable_Disable(HWND hWnd, bool bEnableDisable);
        //DLL_EXP_IMP int WINAPI Thread_Desktop(LPTHREAD_START_ROUTINE ThreadFunc, THREAD_DATA *td);
        //DLL_EXP_IMP int WINAPI Process_Desktop(char *szDesktopName, char *szPath);
        #endregion


        //隐藏鼠标:   Cursor.Hide();   
        //显示鼠标:   Cursor.Show();
     


        private void NetStart_FormClosed(object sender, FormClosedEventArgs e)
        {
            Hook_Clear();
            //CtrlAltDel_Enable_Disable(true);//打开ctrl+alt+del功能
            // Taskbar_Show_Hide(true);//启用任务栏
            //Desktop_Show_Hide(true);//启用桌面显示
            


        }


        private void btnExit_Click(object sender, EventArgs e)
        {
           DialogResult dr= MessageBox.Show("是否确定退出?","友情提示!",MessageBoxButtons.YesNo,MessageBoxIcon.Question);
            if (dr==DialogResult.Yes)
            {
                 Application.Exit();
            }
           
        }






        private void button1_Click_1(object sender, EventArgs e)
        {
            MessageBox.Show("ok");
        }


        private void panel1_MouseEnter(object sender, EventArgs e)
        {
            Size ss=new System.Drawing.Size(label1.Width,30);
            label1.Size = ss;
            label2.Visible = true;
            label3.Visible = true;
        }
        private void panel2_MouseLeave(object sender, EventArgs e)
        {
                Size ss = new Size(label1.Width, 0);
            label1.Size = ss;
            label2.Visible = false;
            label3.Visible = false;
        }


        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
                Application.Exit();
        }


        private void 软帝考试系统_Load(object sender, EventArgs e)
        {
            Thread th = new Thread(new ThreadStart(UdpRecviceMessage));
            th.IsBackground = true;
            th.Start();


            //将鼠标的初始位置设定到form的左上角
            // System.Windows.Forms.Cursor.Position = this.Location;


            //CtrlAltDel_Enable_Disable(false);//禁止ctrl+alt+del
            //Taskbar_Show_Hide(false);//隐藏任务栏
            //Desktop_Show_Hide(false);//隐藏桌面
        }


      


   










  








    }
}
———————————————
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2026 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行