//服务器端代码

 

 

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Drawing.Imaging;

using System.Text;

using System.Windows.Forms;

using System.IO;

using System.Net;

using System.Net.Sockets;

using Microsoft.Win32;

using System.Threading;

namespace 远程屏幕监视

{

    public partial class Form1 : Form

    {

        Socket socket = null;

        Thread th = null;

        string path = string.Empty;

        public Form1()

        {

            InitializeComponent();

        }

        private void Form1_Load(object sender, EventArgs e)

        {

            //如果连接的配置文件不存在,则退出

            path = Path.Combine(Application.StartupPath, "config.ini");

            if (File.Exists(path) == false)

            {

                Application.Exit();

                return;

            }

            //检查注册表项,如果不存在启动项,则加入。

            RegistryKey RootKey = Registry.CurrentUser;

            RegistryKey subKey = null;

            try

            {

                subKey = RootKey.OpenSubKey(@"Software/Microsoft/Windows/CurrentVersion/Run", true);

                if (subKey.GetValue("ScreenViewer") == null)

                {

                    subKey.SetValue("ScreenViewer", Application.ExecutablePath);

                }

                subKey.Close();

            }

            catch {/* 出现错误,则忽略。 */ }

            RootKey.Close();  //关闭注册所有句柄,释放资源

            //连接

            IPAddress ip=null;

            int port=0;

           

            using (StreamReader sr = new StreamReader(path))

            {

                try

                {

                    string s = sr.ReadToEnd();

                    sr.Close();

                    string[] res = s.Split(new char[] {':' });

                    ip = Dns.GetHostAddresses(res[0])[0];

                    port = int.Parse(res[1]);

                }

                catch { }

            }

            try

            {

                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                //连接,循环

                while (true)

                {

                    try

                    {

                        socket.Connect(ip, port);

                        if (socket.Connected)

                        {

                            break;

                        }

                    }

                    catch { Thread.Sleep(5000); }

                }

                ThreadStart sss = new ThreadStart(this.DoReceiveAndWhrite);

                th = new Thread(sss);

                th.Start();

            }

            catch { }

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)

        {

            if (th != null)

            {

                try

                {

                    th.Abort();

                }

                catch { th = null; }

            }

            if (socket != null)

            {

                try

                {

                    socket.Close();

                }

                catch

                {

                }

            }

            //关闭原因

            if (e.CloseReason == CloseReason.TaskManagerClosing ||

                e.CloseReason == CloseReason.WindowsShutDown)

            {

                Application.Exit();       //正常关闭

            }

        }


        /// <summary>

        /// 接收和发送

        /// </summary>

        private void DoReceiveAndWhrite()

        {

            try

            {

                while (true)

                {

                    byte[] buffer =new byte[1024];

                    //接受控制端的消息

                    socket.Blocking = true;

                    int len=socket.Receive(buffer);

                    if (len > 0)

                    {

                        string mss = Encoding.Default.GetString(buffer,0,len);

                        if (mss.Trim() == "<CATCH>") //仅摄屏一次

                        {

                            MemoryStream MS = GetBitmapStream();

                            byte[] tbuffer = new byte[1024];

                            MS.Seek(0, SeekOrigin.Begin);

                            while (MS.Read(tbuffer, 0, 1024) > 0)

                            {

                                socket.Send(tbuffer);//发送

                                tbuffer = new byte[1024];

                            }

                            MS.Close();

                            //结束标记

                            socket.Send(Encoding.Default.GetBytes("OK"));

                        }

                    }

                }

            }

            catch { }

        }

        /// <summary>

        /// 得到图象的内存流

        /// </summary>

        /// <returns></returns>

        private MemoryStream GetBitmapStream()

        {

            int width = Screen.PrimaryScreen.Bounds.Width;//宽

            int height = Screen.PrimaryScreen.Bounds.Height;//高

            //创建位图对象

            Bitmap mybit = new Bitmap(width, height);

            //复制屏幕内容到图象上

            Graphics g = Graphics.FromImage(mybit);

            MemoryStream ms = new MemoryStream();

            try

            {

                g.CopyFromScreen(0, 0, 0, 0, new Size(width, height));

                mybit.Save(ms, ImageFormat.Gif);

            }

            catch { return null; }

            finally

            {

                g.Dispose();

                mybit.Dispose();

                //ms.Close();

            }

            return ms;

        }

    }

}

 

 

 

 

=====================================

//客户端代码

 

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Net;

using System.Net.Sockets;

using System.Threading;

using System.IO;

namespace 客户端

{

    public partial class Form1 : Form

    {

        TcpListener listemer = null;

        Socket socket = null;

        Thread th = null;

        public Form1()

        {

            CheckForIllegalCrossThreadCalls = false;

            InitializeComponent();

            listemer = new TcpListener(IPAddress.Any,18889);

        }

        private void Form1_Load(object sender, EventArgs e)

        {

            button1.Enabled = true;

            button2.Enabled = false;

        }

        private void Do()

        {

            socket = listemer.AcceptSocket();

            textBox1.Text = ((IPEndPoint)socket.RemoteEndPoint).Address.ToString();

            Form2 f = new Form2(socket);

            f.ShowDialog();

        }

        private void button1_Click(object sender, EventArgs e)

        {

            listemer.Start();

            ThreadStart start = new ThreadStart(this.Do);

            th = new Thread(start);

            th.Start();

            button1.Enabled = false;

            button2.Enabled = true;

        }

        private void button2_Click(object sender, EventArgs e)

        {

            listemer.Stop();

            try

            {

                th.Abort();

            }

            catch { }

            button1.Enabled = true;

            button2.Enabled = false;

        }

        private void button3_Click(object sender, EventArgs e)

        {

            if(textBox2.Text=="")

                return;

            string filename = Path.Combine(Application.StartupPath, "config.ini");

            FileStream fsr = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite);

            StreamWriter sw = new StreamWriter(fsr);

            try

            {

                string s = textBox2.Text;

                sw.Write(s + ":18889");

                sw.Flush();

            }

            catch { MessageBox.Show("写入文件失败。"); }

            finally

            {

                sw.Close();

                sw.Dispose();

                fsr.Close();

                fsr.Dispose();

            }

        }

    }

}

 

 

==========================================================================

 

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Net;

using System.Net.Sockets;

using System.Threading;

using System.IO;

namespace 客户端

{

    public partial class Form2 : Form

    {

        Socket mySocket=null;

        public Form2(Socket s)

        {

            InitializeComponent();

            this.mySocket = s;

        }

        private void Form2_Load(object sender, EventArgs e)

        {

        }

        /// <summary>

        /// 获取图象

        /// </summary>

        /// <returns></returns>

        private Image GetBitmap()

        {

            Image mb = null;

            MemoryStream ms = new MemoryStream();

            byte[] buffer = null;

            try

            {

                mySocket.Blocking = true;

                //发送指令

                mySocket.Send(Encoding.Default.GetBytes("<CATCH>"));

                buffer = new byte[1024];

                //把接收到的字节写入内存流

                int count = mySocket.Receive(buffer);

                while (count > 0)

                {

                    string st = Encoding.Default.GetString(buffer,0,count);

                    if (st == "OK")

                    {

                        break;

                    }

                    ms.Write(buffer, 0, buffer.Length);

                    buffer = new byte[1024];

                    count = mySocket.Receive(buffer);

                }

                mb = Image.FromStream(ms);

            }

            catch

            {

                MessageBox.Show("读取远程数据出错。");

                return null;

            }

            finally

            {

                ms.Close();

            }

            return mb;

        }

        private void Form2_KeyDown(object sender, KeyEventArgs e)

        {

            if ((e.Alt == true) && (e.KeyCode == Keys.K))

            {

                this.BackgroundImage = GetBitmap();

                /*

                Graphics g = this.CreateGraphics();

                g.DrawImage(GetBitmap(),new Point(0,0));

                g.Dispose();

                 */

            }

        }

        private void Form2_FormClosing(object sender, FormClosingEventArgs e)

        {

            if (mySocket != null)

            {

                try

                {

                    mySocket.Close();

                }

                catch { }

            }

        }

    }

}