我正在尝试在 C# 中设置一个简单的桌面监控程序。我已经搜索了将近一个小时试图找到一个工作模型,但是我发现的任何东西要么抛出异常,要么太复杂,调用模糊的函数。
我能够将屏幕捕获到位图实例,并且尝试发送它时遇到了困难,但目前,程序正常运行并关闭。客户端抛出异常,因为连接没有正确关闭(懒惰我!),但没有其他任何事情发生。没有输出文件被写入,什么也没有。
这是服务器的代码
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Net;
using System.Net.Sockets;
using System;
class ScreenCapture
{
public static void Main()
{
try
{
TcpListener srv = new TcpListener(IPAddress.Any, 51530);
srv.Start(1);
TcpClient client = srv.AcceptTcpClient();
NetworkStream ns = client.GetStream();
StreamWriter send = new StreamWriter(ns);
StreamReader read = new StreamReader(ns);
Rectangle screenshot;
Bitmap bitmap;
screenshot = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea;
bitmap = new Bitmap(screenshot.Width, screenshot.Height, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(bitmap);
g.CopyFromScreen(screenshot.Left, screenshot.Top, 0, 0, screenshot.Size);
g.Dispose();
MemoryStream m = new MemoryStream();
bitmap.Save(m, ImageFormat.Jpeg);
byte[] data = m.ToArray();
Console.WriteLine(data.ToString());
send.Write(m);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadKey();
}
}
}
这是客户端的代码:
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Drawing;
using System.Drawing.Imaging;
class RetrieveScreenShot
{
public static void Main()
{
try
{
TcpClient client = new TcpClient("127.0.0.1", 51530);
NetworkStream ns = client.GetStream();
Image receivedImage = Image.FromStream(ns);
receivedImage.Save("output.bmp");
ns.Close();
client.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadLine();
}
}
}