| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1152 人关注过本帖
标题:C# 手机使用USB投屏电脑(只适用Android)
只看楼主 加入收藏
qq2889577966
Rank: 4
等 级:业余侠客
威 望:5
帖 子:66
专家分:277
注 册:2021-4-14
结帖率:100%
收藏
已结贴  问题点数:20 回复次数:1 
C# 手机使用USB投屏电脑(只适用Android)
将手机打开“开发人员模式”,然后“允许USB调试”,链接电脑,此过程不会的百度查。
原理:调用adb命令控制手机录屏,输出到一个播放器。
画面流畅不卡。
adb不知道的百度查询。

adb相关操作参考:
https://
播放器参考:
https://
以上均为开源软件,全部源代码。

下载:
链接:https://pan.baidu.com/s/1Ps6terEiFEQD8FdEURju-g
提取码:5b3z

图片附件: 游客没有浏览图片的权限,请 登录注册


程序代码:
using System;
using System.Diagnostics;
using 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 { }
                }
            }
        }
    }
}



[此贴子已经被作者于2022-11-2 08:15编辑过]

收到的鲜花
  • 龙胆草2022-11-02 16:46 送鲜花  1朵   附言:厉害!欢迎为社区添砖加瓦!
搜索更多相关主题的帖子: new string Process false private 
2022-11-01 15:54
龙胆草
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:6
帖 子:55
专家分:230
注 册:2022-6-17
收藏
得分:20 
厉害!向你学习!
2022-11-02 16:46
快速回复:C# 手机使用USB投屏电脑(只适用Android)
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.034243 second(s), 12 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved