1 public partial class Form3 : Form
2 {
3 private VideoCaptureDevice videoSource;
4 private FilterInfoCollection videoDevices;
5
6 public Form3()
7 {
8 InitializeComponent();
9 }
10
11 private void Form3_Load(object sender, EventArgs e)
12 {
13 // 枚举所有视频输入设备
14 videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
15
16 if (videoDevices.Count == 0)
17 {
18 MessageBox.Show("未找到视频输入设备!");
19 return;
20 }
21
22 // 选择第一个视频设备
23 videoSource = new VideoCaptureDevice(videoDevices[0].MonikerString);
24
25 // 为新帧事件添加处理程序
26 videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);
27
28 // 开始捕获视频
29 videoSource.Start();
30 }
31
32 private void videoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
33 {
34 // 获取新帧的图像
35 Bitmap videoFrame = (Bitmap)eventArgs.Frame.Clone();
36
37 // 在 PictureBox 中显示图像
38 videoSourcePlayer.Image = videoFrame;
39 }
40
41 private void btnStart_Click_1(object sender, EventArgs e)
42 {
43 if (videoSourcePlayer.Image != null)
44 {
45 // 生成一个唯一的文件名
46 string fileName = $"capture_{DateTime.Now:yyyyMMddHHmmss}.jpg";
47
48 // 保存图像
49 videoSourcePlayer.Image.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
50
51 MessageBox.Show($"图像已保存为 {fileName}");
52 }
53 }
54
55 private void Form3_FormClosing(object sender, FormClosingEventArgs e)
56 {
57 // 停止视频捕获
58 if (videoSource != null && videoSource.IsRunning)
59 {
60 videoSource.SignalToStop();
61 videoSource.WaitForStop();
62 videoSource = null;
63 }
64 }
65 }