很久没有写文章了,今天分享的内容是局域网桌面共享软件,相信很多人都做过,也可能遇到一些问题,这里我将一一测试。
涉及到的内容有:局域网文件传输、桌面截屏、图片压缩等。为了更直白的演示程序的功能所以没有对代码进行封装。
获取桌面图片,十分简单.
private Bitmap GetScreen()
{
Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics g = Graphics.FromImage(bitmap);
g.CopyFromScreen(, , , , bitmap.Size);
return bitmap;
}
客户端
定义全局变量
Socket sendsocket;
按钮事件(连接服务器,并发送桌面截图)
private void btnConn_Click(object sender, EventArgs e)
{
try
{
sendsocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//实例化socket,ip为192.168.1.106,Port为10001
IPEndPoint ipendpiont = new IPEndPoint(IPAddress.Parse(textBox1.Text.Trim()), );
sendsocket.Connect(ipendpiont);
//建立终结点
Thread th = new Thread(new ThreadStart(threadimage));
th.IsBackground = true;
th.Start();
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
return;
}
this.Hide();//隐藏窗体
}
线程执行体
private void threadimage()
{
try
{
while (true)
{
MemoryStream ms = new MemoryStream();
GetScreen().Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);//我这里用bmp格式
byte[] b = ms.ToArray();
sendsocket.Send(b);
Thread.Sleep();//我这里设置1秒发送一次
}
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
return;
}
}
服务端(窗体中有一个PictureBox)
定义全局变量
Socket hostSocket;
Thread thread;
按钮事件(开启服务)
private void btnStart_Click(object sender, EventArgs e)
{
Socket receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint hostIpEndPoint = new IPEndPoint(IPAddress.Parse(textBox1.Text.Trim()), );
//关联结点
receiveSocket.Bind(hostIpEndPoint);
receiveSocket.Listen();
MessageBox.Show("start");
hostSocket = receiveSocket.Accept(); thread = new Thread(new ThreadStart(trreadimage));
thread.IsBackground = true;
thread.Start();
}
线程执行体
private void trreadimage()
{
try
{
while (true)
{
byte[] b = new byte[ * ];//图片很大
hostSocket.Receive(b);
MemoryStream ms = new MemoryStream(b);
Image img=Image.FromStream(ms);
picReceive.Image = img;
}
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
thread.Abort();
}
}
如果你去测试这个程序就会发现存在一些问题,后面我将处理你所遇到的问题。
由于程序简单所以就不上传源码附件了。
C#局域网桌面共享软件制作(二)
转载,请注明出处和相关链接,否则追究其法律责任!