实例介绍
【实例简介】C# 手机使用USB投屏电脑(只适用Android)
将手机打开“开发人员模式”,然后“允许USB调试”,链接电脑,此过程不会的百度查。
原理:调用adb命令控制手机录屏,输出到一个播放器。
画面流畅不卡。
adb不知道的百度查询。
adb相关操作参考:
https://github.com/TGSAN/MirrorCaster
播放器参考:
https://github.com/mpv-player/mpv
以上均为开源软件,全部源代码。
using System;
using System.Diagnostics;
using System.IO.Pipes;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace Phone_Demo
{
public partial class Form1 : Form
{
public class DeviceInfoData
{
public int deviceWidth = 1920;
public int deviceHeight = 1080;
public double deviceRefreshRate = 60;
public bool deviceVmode = false;
}
private Process stdoutProcess = null;
private Process stdinProcess = null;
private StreamPipe rePipe;
private readonly DeviceInfoData deviceInfoData = new DeviceInfoData();
private readonly DeviceInfoData instartDeviceInfoData = new DeviceInfoData();
private double castMbitRate = 30;
public Form1()
{
InitializeComponent();
this.FormClosed = (s, e) => { Kill_Process("adb"); };
}
private void button1_Click(object sender, EventArgs e)
{
StopCast();
if (UpdateScreenDeviceInfo())
{
StartCast();
}
}
private void StartCast()
{
stdoutProcess = new Process();
stdinProcess = new Process();
StdOut();
StdIn();
rePipe = new StreamPipe(stdoutProcess.StandardOutput.BaseStream, stdinProcess.StandardInput.BaseStream);
rePipe.Connect();
instartDeviceInfoData.deviceVmode = deviceInfoData.deviceVmode; // 记录播放时的横竖屏状态
}
private void StopCast()
{
try
{
try
{
if (stdoutProcess != null)
{
stdoutProcess.Exited -= StdIOProcess_Exited;
stdoutProcess.Kill();
stdoutProcess = null;
}
}
catch (Exception ex)
{
MessageBox.Show("无法关闭StdOUT," ex.Message);
}
try
{
if (stdinProcess != null)
{
stdinProcess.Exited -= StdIOProcess_Exited;
stdinProcess.Kill();
stdoutProcess = null;
}
}
catch (Exception ex)
{
MessageBox.Show("无法关闭StdIN," ex.Message);
}
if (rePipe != null)
{
rePipe.Disconnect();
}
}
catch (Exception ex)
{
MessageBox.Show("无法断开重定向," ex.Message);
}
nosigalLabel.Text = "等一下...,滑动手机屏幕";
}
private string ADBResult(string args)
{
Process process = new Process();
process.StartInfo.FileName = System.AppDomain.CurrentDomain.BaseDirectory @"lib\adb\adb.exe";
process.StartInfo.Arguments = args;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.StandardOutputEncoding = Encoding.UTF8;
process.Start();
string result = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadLine();
process.Close();
return error result;
}
private bool UpdateScreenDeviceInfo()
{
string str = ADBResult("shell \"dumpsys window displays && dumpsys SurfaceFlinger\"").ToLower();
if (str.StartsWith("error: no devices/emulators found"))
{
MessageBox.Show("找不到任何设备或模拟器");
return false;
}
else if (str.StartsWith("error: more than one device/emulator"))
{
MessageBox.Show("暂时只支持单个设备开启 ADB 调试");
return false;
}
Regex regexSize = new Regex(@"\s cur=(?<width>[0-9]*)x(?<height>[0-9]*?)\s ", RegexOptions.Multiline);
Match matchSize = regexSize.Match(str);
Regex regexRefreshRate = new Regex(@"\s refresh-rate. ?(?<refreshRate>[0-9]*\.{0,1}[0-9]*?)\s*fps\s ", RegexOptions.Multiline);
Match matchRefreshRate = regexRefreshRate.Match(str);
if (matchSize.Success)
{
try
{
int width = int.Parse(matchSize.Groups["width"].Value); //宽
int height = int.Parse(matchSize.Groups["height"].Value); //高
bool vmode = true; //垂直
if (width > height)
{
vmode = false; //水平
}
deviceInfoData.deviceWidth = width;
deviceInfoData.deviceHeight = height;
deviceInfoData.deviceVmode = vmode;
}
catch { }
}
if (matchRefreshRate.Success)
{
try
{
double refreshRate = double.Parse(matchRefreshRate.Groups["refreshRate"].Value);
deviceInfoData.deviceRefreshRate = refreshRate;
}
catch { }
}
return true;
}
private void StdIOProcess_Exited(object sender, EventArgs e)
{
StopCast();
}
/// adb 录屏控制
private void StdOut()
{
stdoutProcess.StartInfo.FileName = @"lib\adb\adb.exe";
stdoutProcess.StartInfo.Arguments = $"exec-out \"while true;do screenrecord --bit-rate={(int)(castMbitRate * 1000000)} --output-format=h264 --size {deviceInfoData.deviceWidth.ToString()}x{deviceInfoData.deviceHeight.ToString()} - ;done\""; //
stdoutProcess.StartInfo.UseShellExecute = false;
stdoutProcess.StartInfo.RedirectStandardOutput = true;
stdoutProcess.StartInfo.CreateNoWindow = true;
stdoutProcess.EnableRaisingEvents = true;
stdoutProcess.Exited = StdIOProcess_Exited;
stdoutProcess.Start();
if (stdinProcess.StartInfo.FileName.Length != 0)
{
stdinProcess.CancelOutputRead();
stdinProcess.Close();
}
}
/// 播放器控制
private void StdIn()
{
string widArg = $"--wid={screenBox.Handle.ToInt64().ToString()}";
string vsyncArgs = "--d3d11-sync-interval=" (false ? "1" : "0");
string releaseArgs = "--input-default-bindings=no --osd-level=0";
string fpsControlArgs = false ? $"--no-correct-pts --fps={deviceInfoData.deviceRefreshRate}" : "--untimed";
string hwdecArgs = true ? "--hwdec=yes" : "--hwdec=no";
string mpvFullArgs = $"--title=\"Phone Demo\" --cache=no --no-cache --profile=low-latency --framedrop=decoder {vsyncArgs} --scale=spline36 --cscale=spline36 --dscale=mitchell --correct-downscaling=yes --linear-downscaling=yes --sigmoid-upscaling=yes {fpsControlArgs} --video-latency-hacks=yes --vo=gpu {hwdecArgs} --no-audio --no-config --no-border -no-osc --no-taskbar-progress {releaseArgs} {widArg} -";
Console.WriteLine("MPV ARGS:\r\n" mpvFullArgs);
stdinProcess.StartInfo.FileName = @"lib\mpv\mpv.exe";
stdinProcess.StartInfo.Arguments = mpvFullArgs;
stdinProcess.StartInfo.UseShellExecute = false;
stdinProcess.StartInfo.RedirectStandardOutput = true;
stdinProcess.StartInfo.RedirectStandardInput = true;
stdinProcess.StartInfo.CreateNoWindow = true;
stdinProcess.EnableRaisingEvents = true;
stdinProcess.Exited = StdIOProcess_Exited;
stdinProcess.Start();
stdinProcess.BeginOutputReadLine();
}
/// 删除进程
private void Kill_Process(string processName)
{
foreach (Process p in Process.GetProcesses())
{
if (p.ProcessName.Contains(processName))
{
try
{
p.Kill();
p.WaitForExit();
}
catch { }
}
}
}
}
}
【实例截图】
【核心代码】
.├── C# 手机使用USB投屏电脑(只适用Android).rar
└── Phone_Demo
├── Phone_Demo
│ ├── App.config
│ ├── Form1.Designer.cs
│ ├── Form1.cs
│ ├── Form1.resx
│ ├── Phone_Demo.csproj
│ ├── Program.cs
│ ├── Properties
│ │ ├── AssemblyInfo.cs
│ │ ├── Resources.Designer.cs
│ │ ├── Resources.resx
│ │ ├── Settings.Designer.cs
│ │ └── Settings.settings
│ ├── StreamPipe.cs
│ ├── bin
│ │ └── Debug
│ │ ├── Phone_Demo.exe
│ │ ├── Phone_Demo.exe.config
│ │ ├── Phone_Demo.pdb
│ │ └── lib
│ │ ├── adb
│ │ │ ├── AdbWinApi.dll
│ │ │ ├── AdbWinUsbApi.dll
│ │ │ ├── adb.exe
│ │ │ └── libwinpthread-1.dll
│ │ └── mpv
│ │ ├── d3dcompiler_43.dll
│ │ └── mpv.exe
│ └── obj
│ └── Debug
└── Phone_Demo.sln
10 directories, 23 files
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明


网友评论
我要评论