屏幕录制现在已经变得非常常见了。不管是做教程视频、游戏直播,还是记录会议内容,一款好用的录屏工具都能让我们轻松抓取画面,并分享重要的瞬间。接下来,本文会一步步教你如何用 C# 和 FFmpeg 打造一个简单却实用的屏幕录制程序。
FFmpeg 是一个强大的开源音频与视频处理工具,支持几乎所有的音视频格式。结合 C# 的界面设计,我们可以快速构建出一个用户友好的录屏应用程序。本文将逐步引导您如何实现这一功能。
在开始之前,请确保您已经安装了以下软件:
AppRecordScreen
。接下来,您需要编写录屏的核心代码。以下是实现屏幕录制的完整代码:
C#using System.Diagnostics;
namespace AppRecordScreen
{
public partial class Form1 : Form
{
// 录屏相关变量
private bool isRecording = false;
private Process ffmpegProcess;
private string outputVideoPath;
// FFmpeg可执行文件的完整路径
private string ffmpegPath = @"D:\Software\ffmpeg-master-latest-win64-gpl-shared\bin\ffmpeg.exe";
public Form1()
{
InitializeComponent();
}
private async void btnStart_Click(object sender, EventArgs e)
{
if (!isRecording)
{
StartRecording();
}
}
private void btnStop_Click(object sender, EventArgs e)
{
if (isRecording)
{
StopRecording();
}
}
/// <summary>
/// 开始录制屏幕
/// </summary>
private void StartRecording()
{
// 生成唯一的视频文件名
outputVideoPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
$"ScreenRecord_{DateTime.Now:yyyyMMdd_HHmmss}.mp4"
);
try
{
// 使用FFmpeg进行屏幕录制
ffmpegProcess = new Process
{
StartInfo = new ProcessStartInfo
{
// 使用完整路径
FileName = ffmpegPath,
Arguments = $"-f gdigrab -framerate 30 -i desktop -c:v libx264 -preset ultrafast {outputVideoPath}",
UseShellExecute = false,
RedirectStandardInput = true,
CreateNoWindow = true
}
};
ffmpegProcess.Start();
isRecording = true;
MessageBox.Show("录制已开始", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show($"启动录制失败:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// 停止录制屏幕
/// </summary>
private void StopRecording()
{
try
{
// 发送 'q' 命令给 FFmpeg 进程以正常结束录制
ffmpegProcess.StandardInput.WriteLine("q");
ffmpegProcess.WaitForExit();
isRecording = false;
MessageBox.Show($"录制已完成。视频保存在:{outputVideoPath}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show($"停止录制失败:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// 在关闭窗体时确保停止录制
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (isRecording)
{
StopRecording();
}
}
}
}
StartRecording
方法将被调用,生成一个带有时间戳的唯一视频文件名,并启动 FFmpeg 进程进行屏幕录制。StopRecording
方法会发送结束命令给 FFmpeg 进程,停止录制并保存视频。通过这篇文章,您学会了如何使用 C# 和 FFmpeg 来创建一个简单的屏幕录制工具。这不仅仅是一个学习项目,您还可以在此基础上不断扩展功能,例如添加视频格式选择、录音功能等。希望您能通过这个工具轻松捕获生活和工作中的重要时刻!
本文作者:技术老小子
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!