C# Winform WPF DeskBand 窗体嵌入任务栏,在任务栏突显文字

   
近来写了个小程序,用于将机械硬盘的写入量等信息体现在任务栏,最开首运用Windows
API也得以实现,不过当任务栏托盘扩张的时候,会被遮住,最终使用了DeskBand来贯彻,填了不少坑。

效果图

gif1

gif2

由于licecap录制的GIF失帧太严重, 都模糊掉了, 再放两张高清截图

png1

png2

    参考的GitHub地址:https://github.com/dsafa/CSDeskBand

前言

当年六月份,斗鱼腾讯领投的1亿欧元融资的音讯被各大平台报道转载,在电竞、泛娱乐已是热门投资的即时,网络直播平台自然也博得了各行各业的眷顾。盗用两张有关游戏直播的大方向图

游玩直播规模

娱乐直播规模

这还只是是一日游直播这块的蛋糕.直播行业的竞争会愈加猛烈,
不管是主播依然直播平台都面临着激烈的竞争, 当然直播行业也会进一步规范,
直播元素也越来越多.

    DeskBand相关代码如下:

视频直播初窥

视频直播,可以分成 采集,前处理,编码,传输, 服务器处理,解码,渲染

  • 募集: iOS系统因为软硬件类别不多, 硬件适配性相比好, 所以相比较简单.
    而Android端市面上机型众多, 要做些机型的适配工作.PC端是最劳顿的,
    各个奇葩版画头驱动.所以现在无数的中小型直播平台, 都放任了PC的直播,
    更有一对直播平台只做iOS端的视频直播.

  • 前处理: 美颜算法,视频的模糊效果, 水印等都是在这些环节做.
    近年来iOS端最显赫开源框架的自然就是GPUImage.其中内置了125种渲染效果,
    还辅助各种本子自定义. 我高仿的喵播的美颜功效也是遵照GPUImage的.

  • 编码:
    重难点在于要在分辨率,帧率,码率,GOP等参数设计上找到最佳平衡点。iOS8过后,
    Apple开放了VideoToolbox.framework, 能够直接举办硬编解码,
    这也是干吗现在大部分直播平台最低只帮忙到iOS8的缘由之一.
    iOS端硬件兼容性相比好, 可以一贯运用硬编码.
    而Android得硬编码又是一大坑.

  • 传输: 这块一般都是付诸CDN服务商.
    CDN只提供带宽和服务器之间的传输,
    发送端和接收端的网络连接抖动缓存如故要和谐实现的.近期国内最大的CDN服务商应该是网宿.

  • 服务器处理: 需要在服务器做一些流处理工作,
    让推送上来的流适配各类平台各个不同的情商, 比如:RTMP,HLS,FLV…

  • 解码和渲染: 也就即音视频的播放. 解码毫无疑问也不可能不要硬解码.
    iOS端兼容较好, Android依旧大坑.这块的困难在于音画同步,
    最近广大直播平台这块是硬伤.国内相比较好的开源项目相应是B站开源的<a
    href=”https://github.com/Bilibili/ijkplayer"&gt;ijkplayer
    </a>. 斗鱼就是按照<a
    href=”https://github.com/Bilibili/ijkplayer"&gt;ijkplayer
    </a>的, 本项目也是依照<a
    href=”https://github.com/Bilibili/ijkplayer"&gt;ijkplayer
    </a>的.

技能坑 : 降噪, 音频解码器, 蓝牙适配, 回声消除, 信令控制, 登录, 鉴权,
权限管理, 状态管理, 应用信息, 信息推送, 礼物系统, 即时拉扯, 支付系统,
总括连串, 数据库, 缓存, 分布式文件存储, 音信队列,
运维系统等等大小不一的坑等你来填!!!

基金坑 : 以带宽为例, 2万人同时在线, 手机码率在600KB,
每个月的带宽费用至少在30万左右. 基于欢聚时代(YY)15年四季度财务报,
他们的带宽成本为人民币1.611亿元, 折合每月5000万+.
人力财力+渠道支出和其他支出就一无所知谈了.

社会坑: 还得每一日与各样黑暗势力斗争, 包括色情, 广告, 刷中号,
刷充值, 告侵权, DDos…(我反编译喵播的官方APP,
他们的品种名就叫Shehui, O(∩_∩)O哈哈~)

COLORREF:

品种下载地址

<a
href=”https://github.com/SunLiner/MiaowShow"&gt;GitHub下载地址&lt;/a&gt;

图片 1图片 2

中期准备

品类根本是遵照<a
href=”https://github.com/Bilibili/ijkplayer"&gt;ijkplayer </a>的.
最好是打包成framework. 原本我准备写一个包裹教程,
不过后来在简书上发现了一篇专门详细的打包blog, 分享给我们: <a
href=”http://www.jianshu.com/p/1f06b27b3ac0"&gt;http://www.jianshu.com/p/1f06b27b3ac0&lt;/a&gt;.

即使您依据教程打包退步了(当然那种概率相比小),
我这还有一份本身一度打包好的(Release版), 下载地址:
链接:http://pan.baidu.com/s/1eRVetdK
密码:2dc0
下载后, 直接解压即可.

// This code snippet was used by SharpShell.
//

using System.Drawing;
using System.Runtime.InteropServices;

namespace MyDiskInfo.Interop
{
    [StructLayout(LayoutKind.Sequential)]
    public struct COLORREF
    {
        public COLORREF(Color color)
        {
            Dword = (uint)color.R + (((uint)color.G) << 8) + (((uint)color.B) << 16);
        }

        public uint Dword;
        public Color Color
        {
            get
            {
                return Color.FromArgb(
                    (int)(0x000000FFU & Dword),
                    (int)(0x0000FF00U & Dword) >> 8,
                    (int)(0x00FF0000U & Dword) >> 16);
            }
        }
    }
}

花色文件结构

  • Frameworks: 假如文件夹不设有, 点击classes选择Show in Finder,
    新建一个即可, 将您打包的或者下载的framework拖入其中并拉进项目中.
    你也足以友善建一个文件夹, 把这一个Frameworks直接delete即可

  • Profile : 个人主题, 这其间唯有一个ProfileController.
    因为总写重复代码, 都写吐了, 这儿有趣味的友善写一下吗, So easy…

  • Network : 关于网络连接的工具类. 关于网络的实时监控, 网络状态的切换,
    网络请求的工具类都在这里面.

  • Other : 全局的常量. 当然你也可以在里头将文件结构进一步细化.

  • Home : 包含最新主播, 最热直播, 关注的直播, 礼物排行榜等模块.
    还有最重大的视频直播也在这之中了.

  • ShowTime :见名知意. 录像直播的前处理,
    智能美颜和H264硬编码等都在这边面.

  • Main : UITabBarControllerUINavigationController的配置

  • Toos : 这儿命名有点不标准, 这之中放置的都是系列用到的分类

  • Login : 登录模块

  • Resource : 项目用到的资源文件

View Code

品种详解

  • tip1: 判读网络类型.

在察看直播的时候, 大家日常都是用WiFi或者3/4G(土豪级其它),
一般用户在进展网络切换的时候, 我们都要提交友善的提示, 告诉TA:
您的网络状态切换来了XX状态. 倘诺用户从WiFi切换来4G,
你的应用也没个提示, 导致TA的流量归零甚至欠了运营商一屁股的钱,
我想你的APP的用户体验也就归零或者为负了.

俺们能够接纳苹果的Reachability构成上边的代码实时监听网络状态的变更

typedef NS_ENUM(NSUInteger, NetworkStates) {
    NetworkStatesNone, // 没有网络
    NetworkStates2G, // 2G
    NetworkStates3G, // 3G
    NetworkStates4G, // 4G
    NetworkStatesWIFI // WIFI
};

// 判断网络类型
+ (NetworkStates)getNetworkStates
{
    NSArray *subviews = [[[[UIApplication sharedApplication] valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];
    // 保存网络状态
    NetworkStates states = NetworkStatesNone;
    for (id child in subviews) {
        if ([child isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
            //获取到状态栏码
            int networkType = [[child valueForKeyPath:@"dataNetworkType"] intValue];
            switch (networkType) {
                case 0:
                   //无网模式
                    states = NetworkStatesNone;
                    break;
                case 1:
                    states = NetworkStates2G;
                    break;
                case 2:
                    states = NetworkStates3G;
                    break;
                case 3:
                    states = NetworkStates4G;
                    break;
                case 5:
                {
                    states = NetworkStatesWIFI;
                }
                    break;
                default:
                    break;
            }
        }
    }
    //根据状态选择
    return states;
}
  • tip2: 登录模块

假设你多运行五回就会发现,
登录模块背景中播放的视频是2个摄像每便随机播放一个的.并且是最最重复的,
也就是说只要你一贯呆着登录界面, 就会单视频循环播放当下的视频.
这儿的登录只是多少个按钮, 没有切实可行的报到逻辑,
随便点哪一个按钮都得以进来首页.

俺们需要监听视频, 是否播放完成.

// 监听视频是否播放完成
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didFinish) name:IJKMPMoviePlayerPlaybackDidFinishNotification object:nil];

万一播放完成了, 让IJKFFMoviePlayerController再次play即可

- (void)didFinish
{
    // 播放完之后, 继续重播
    [self.player play];
}
  • tip3: 首页

首页

这种意义相信广大人都见到过依然做过.我大概说一下自己的做法(不必然是顶级的,
只是提供一个思路)

一个父控制器HomeViewController+三个子控制器(最热/最新/关注.
每个控制器各自管理自己的政工逻辑, 高内聚低耦合).
重写HomeViewControllerloadView,
self.view替换成UIScrollView.
将两个子控制器的view添加到UIScrollView上即可. 其他的效能落实,
请参照我的代码, 都有详尽的国语注释.

  • tip4: 直播(面向观众端)
    本条是百分之百项目标重中之重之一了.这种直播的布局, 应该是相比较主流的了.
    我下载的广大直播类APP都是这一个体系布局,
    包括YY也是这种界面布局.这些里面涉及的事物相比较多了, 三言两语真说不清.

一句话来说说一下早就落实的效能:
A: 主播的直播
B: 关联主播的录像直播, 默认是只有界面, 没有动静的.
点击该视图可以切换来此主播
C: 下拉切换另一个主播, 这多少个功能是很广阔的.
做法是直播控制器是一个UICollectionViewController, 只有一个cell,
cell.frame就是self.collectionViewb.bounds.
大家进来直播控制器的时候, 其实是传进去一个关系主播数组,
每一趟下拉的时候, 就加载数组里面的主播
D. 查看观众席的观众详情
E. 查看主播详情
F. 足迹: 粒子动画, 前边详解
G. 弹幕: 点击最下方的工具栏第一个按钮能够开启/关闭弹幕, 前面详解

  • tip5: 粒子动画实现游客足迹
    粒子动画的layer是添加到播放器的view上边的. 下边代码有详细的注释

CAEmitterLayer *emitterLayer = [CAEmitterLayer layer];
// 发射器在xy平面的中心位置
emitterLayer.emitterPosition = CGPointMake(self.moviePlayer.view.frame.size.width-50,self.moviePlayer.view.frame.size.height-50);
// 发射器的尺寸大小
emitterLayer.emitterSize = CGSizeMake(20, 20);
// 渲染模式
emitterLayer.renderMode = kCAEmitterLayerUnordered;
// 开启三维效果
//    _emitterLayer.preservesDepth = YES;
NSMutableArray *array = [NSMutableArray array];
// 创建粒子
for (int i = 0; i<10; i++) {
    // 发射单元
    CAEmitterCell *stepCell = [CAEmitterCell emitterCell];
    // 粒子的创建速率,默认为1/s
    stepCell.birthRate = 1;
    // 粒子存活时间
    stepCell.lifetime = arc4random_uniform(4) + 1;
    // 粒子的生存时间容差
    stepCell.lifetimeRange = 1.5;
    // 颜色
    // fire.color=[[UIColor colorWithRed:0.8 green:0.4 blue:0.2 alpha:0.1]CGColor];
    UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"good%d_30x30", i]];
    // 粒子显示的内容
    stepCell.contents = (id)[image CGImage];
    // 粒子的名字
    //            [fire setName:@"step%d", i];
    // 粒子的运动速度
    stepCell.velocity = arc4random_uniform(100) + 100;
    // 粒子速度的容差
    stepCell.velocityRange = 80;
    // 粒子在xy平面的发射角度
    stepCell.emissionLongitude = M_PI+M_PI_2;;
    // 粒子发射角度的容差
    stepCell.emissionRange = M_PI_2/6;
    // 缩放比例
    stepCell.scale = 0.3;
    [array addObject:stepCell];
}

emitterLayer.emitterCells = array;
[self.moviePlayer.view.layer insertSublayer:emitterLayer below:self.catEarView.layer];

 _renderer = [[BarrageRenderer alloc] init];
// 设置弹幕的显示区域. 基于父控件的.
_renderer.canvasMargin = UIEdgeInsetsMake(ALinScreenHeight * 0.3, 10, 10, 10);
[self.contentView addSubview:_renderer.view];

弹幕配置

#pragma mark - 弹幕描述符生产方法
/// 生成精灵描述 - 过场文字弹幕
- (BarrageDescriptor *)walkTextSpriteDescriptorWithDirection:(NSInteger)direction
{
    BarrageDescriptor * descriptor = [[BarrageDescriptor alloc]init];
    descriptor.spriteName = NSStringFromClass([BarrageWalkTextSprite class]);
    descriptor.params[@"text"] = self.danMuText[arc4random_uniform((uint32_t)self.danMuText.count)];
    descriptor.params[@"textColor"] = Color(arc4random_uniform(256), arc4random_uniform(256), arc4random_uniform(256));
    descriptor.params[@"speed"] = @(100 * (double)random()/RAND_MAX+50);
    descriptor.params[@"direction"] = @(direction);
    descriptor.params[@"clickAction"] = ^{
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"弹幕被点击" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
        [alertView show];
    };
    return descriptor;
}

最终一步, 千万要记得start

[_renderer start];
  • tip7: 智能美颜功用
    今昔的直播平台, 美颜是标配.
    不然绝大多数的主播都是无可奈何看的.美颜算法需要用到GPU编程,
    需要懂图像处理的人. 图像处理这一块我不是很熟谙,
    相关的文献也是看得云里雾里的. 所以, 如故采用开源的轮子:<a
    href=”https://github.com/BradLarson/GPUImage"&gt; GPUImage
    </a>. 这一个开源框架有近1.3W+star(三月5日多少), 真不是盖的,
    内置125种滤镜效果, 没有你不意, 唯有你不会用.
    我的项目中都有详实的用法, 仍然很简单的.
    在此处摘抄一份其.h文件的注释. 一方面有利于我们修改我项目中的美颜效率,
    另一方面也是做个备份.(具体出处自己真忘了, 要是有人找到了源地址链接,
    可以联系自身加上)

#import "GLProgram.h"

// Base classes
#import "GPUImageOpenGLESContext.h"
#import "GPUImageOutput.h"
#import "GPUImageView.h"
#import "GPUImageVideoCamera.h"
#import "GPUImageStillCamera.h"
#import "GPUImageMovie.h"
#import "GPUImagePicture.h"
#import "GPUImageRawDataInput.h"
#import "GPUImageRawDataOutput.h"
#import "GPUImageMovieWriter.h"
#import "GPUImageFilterPipeline.h"
#import "GPUImageTextureOutput.h"
#import "GPUImageFilterGroup.h"
#import "GPUImageTextureInput.h"
#import "GPUImageUIElement.h"
#import "GPUImageBuffer.h"

// Filters
#import "GPUImageFilter.h"
#import "GPUImageTwoInputFilter.h"


#pragma mark - 调整颜色 Handle Color

#import "GPUImageBrightnessFilter.h"                //亮度
#import "GPUImageExposureFilter.h"                  //曝光
#import "GPUImageContrastFilter.h"                  //对比度
#import "GPUImageSaturationFilter.h"                //饱和度
#import "GPUImageGammaFilter.h"                     //伽马线
#import "GPUImageColorInvertFilter.h"               //反色
#import "GPUImageSepiaFilter.h"                     //褐色(怀旧)
#import "GPUImageLevelsFilter.h"                    //色阶
#import "GPUImageGrayscaleFilter.h"                 //灰度
#import "GPUImageHistogramFilter.h"                 //色彩直方图,显示在图片上
#import "GPUImageHistogramGenerator.h"              //色彩直方图
#import "GPUImageRGBFilter.h"                       //RGB
#import "GPUImageToneCurveFilter.h"                 //色调曲线
#import "GPUImageMonochromeFilter.h"                //单色
#import "GPUImageOpacityFilter.h"                   //不透明度
#import "GPUImageHighlightShadowFilter.h"           //提亮阴影
#import "GPUImageFalseColorFilter.h"                //色彩替换(替换亮部和暗部色彩)
#import "GPUImageHueFilter.h"                       //色度
#import "GPUImageChromaKeyFilter.h"                 //色度键
#import "GPUImageWhiteBalanceFilter.h"              //白平横
#import "GPUImageAverageColor.h"                    //像素平均色值
#import "GPUImageSolidColorGenerator.h"             //纯色
#import "GPUImageLuminosity.h"                      //亮度平均
#import "GPUImageAverageLuminanceThresholdFilter.h" //像素色值亮度平均,图像黑白(有类似漫画效果)

#import "GPUImageLookupFilter.h"                    //lookup 色彩调整
#import "GPUImageAmatorkaFilter.h"                  //Amatorka lookup
#import "GPUImageMissEtikateFilter.h"               //MissEtikate lookup
#import "GPUImageSoftEleganceFilter.h"              //SoftElegance lookup




#pragma mark - 图像处理 Handle Image

#import "GPUImageCrosshairGenerator.h"              //十字
#import "GPUImageLineGenerator.h"                   //线条

#import "GPUImageTransformFilter.h"                 //形状变化
#import "GPUImageCropFilter.h"                      //剪裁
#import "GPUImageSharpenFilter.h"                   //锐化
#import "GPUImageUnsharpMaskFilter.h"               //反遮罩锐化

#import "GPUImageFastBlurFilter.h"                  //模糊
#import "GPUImageGaussianBlurFilter.h"              //高斯模糊
#import "GPUImageGaussianSelectiveBlurFilter.h"     //高斯模糊,选择部分清晰
#import "GPUImageBoxBlurFilter.h"                   //盒状模糊
#import "GPUImageTiltShiftFilter.h"                 //条纹模糊,中间清晰,上下两端模糊
#import "GPUImageMedianFilter.h"                    //中间值,有种稍微模糊边缘的效果
#import "GPUImageBilateralFilter.h"                 //双边模糊
#import "GPUImageErosionFilter.h"                   //侵蚀边缘模糊,变黑白
#import "GPUImageRGBErosionFilter.h"                //RGB侵蚀边缘模糊,有色彩
#import "GPUImageDilationFilter.h"                  //扩展边缘模糊,变黑白
#import "GPUImageRGBDilationFilter.h"               //RGB扩展边缘模糊,有色彩
#import "GPUImageOpeningFilter.h"                   //黑白色调模糊
#import "GPUImageRGBOpeningFilter.h"                //彩色模糊
#import "GPUImageClosingFilter.h"                   //黑白色调模糊,暗色会被提亮
#import "GPUImageRGBClosingFilter.h"                //彩色模糊,暗色会被提亮
#import "GPUImageLanczosResamplingFilter.h"         //Lanczos重取样,模糊效果
#import "GPUImageNonMaximumSuppressionFilter.h"     //非最大抑制,只显示亮度最高的像素,其他为黑
#import "GPUImageThresholdedNonMaximumSuppressionFilter.h" //与上相比,像素丢失更多

#import "GPUImageSobelEdgeDetectionFilter.h"        //Sobel边缘检测算法(白边,黑内容,有点漫画的反色效果)
#import "GPUImageCannyEdgeDetectionFilter.h"        //Canny边缘检测算法(比上更强烈的黑白对比度)
#import "GPUImageThresholdEdgeDetectionFilter.h"    //阈值边缘检测(效果与上差别不大)
#import "GPUImagePrewittEdgeDetectionFilter.h"      //普瑞维特(Prewitt)边缘检测(效果与Sobel差不多,貌似更平滑)
#import "GPUImageXYDerivativeFilter.h"              //XYDerivative边缘检测,画面以蓝色为主,绿色为边缘,带彩色
#import "GPUImageHarrisCornerDetectionFilter.h"     //Harris角点检测,会有绿色小十字显示在图片角点处
#import "GPUImageNobleCornerDetectionFilter.h"      //Noble角点检测,检测点更多
#import "GPUImageShiTomasiFeatureDetectionFilter.h" //ShiTomasi角点检测,与上差别不大
#import "GPUImageMotionDetector.h"                  //动作检测
#import "GPUImageHoughTransformLineDetector.h"      //线条检测
#import "GPUImageParallelCoordinateLineTransformFilter.h" //平行线检测

#import "GPUImageLocalBinaryPatternFilter.h"        //图像黑白化,并有大量噪点

#import "GPUImageLowPassFilter.h"                   //用于图像加亮
#import "GPUImageHighPassFilter.h"                  //图像低于某值时显示为黑


#pragma mark - 视觉效果 Visual Effect

#import "GPUImageSketchFilter.h"                    //素描
#import "GPUImageThresholdSketchFilter.h"           //阀值素描,形成有噪点的素描
#import "GPUImageToonFilter.h"                      //卡通效果(黑色粗线描边)
#import "GPUImageSmoothToonFilter.h"                //相比上面的效果更细腻,上面是粗旷的画风
#import "GPUImageKuwaharaFilter.h"                  //桑原(Kuwahara)滤波,水粉画的模糊效果;处理时间比较长,慎用

#import "GPUImageMosaicFilter.h"                    //黑白马赛克
#import "GPUImagePixellateFilter.h"                 //像素化
#import "GPUImagePolarPixellateFilter.h"            //同心圆像素化
#import "GPUImageCrosshatchFilter.h"                //交叉线阴影,形成黑白网状画面
#import "GPUImageColorPackingFilter.h"              //色彩丢失,模糊(类似监控摄像效果)

#import "GPUImageVignetteFilter.h"                  //晕影,形成黑色圆形边缘,突出中间图像的效果
#import "GPUImageSwirlFilter.h"                     //漩涡,中间形成卷曲的画面
#import "GPUImageBulgeDistortionFilter.h"           //凸起失真,鱼眼效果
#import "GPUImagePinchDistortionFilter.h"           //收缩失真,凹面镜
#import "GPUImageStretchDistortionFilter.h"         //伸展失真,哈哈镜
#import "GPUImageGlassSphereFilter.h"               //水晶球效果
#import "GPUImageSphereRefractionFilter.h"          //球形折射,图形倒立

#import "GPUImagePosterizeFilter.h"                 //色调分离,形成噪点效果
#import "GPUImageCGAColorspaceFilter.h"             //CGA色彩滤镜,形成黑、浅蓝、紫色块的画面
#import "GPUImagePerlinNoiseFilter.h"               //柏林噪点,花边噪点
#import "GPUImage3x3ConvolutionFilter.h"            //3x3卷积,高亮大色块变黑,加亮边缘、线条等
#import "GPUImageEmbossFilter.h"                    //浮雕效果,带有点3d的感觉
#import "GPUImagePolkaDotFilter.h"                  //像素圆点花样
#import "GPUImageHalftoneFilter.h"                  //点染,图像黑白化,由黑点构成原图的大致图形


#pragma mark - 混合模式 Blend

#import "GPUImageMultiplyBlendFilter.h"             //通常用于创建阴影和深度效果
#import "GPUImageNormalBlendFilter.h"               //正常
#import "GPUImageAlphaBlendFilter.h"                //透明混合,通常用于在背景上应用前景的透明度
#import "GPUImageDissolveBlendFilter.h"             //溶解
#import "GPUImageOverlayBlendFilter.h"              //叠加,通常用于创建阴影效果
#import "GPUImageDarkenBlendFilter.h"               //加深混合,通常用于重叠类型
#import "GPUImageLightenBlendFilter.h"              //减淡混合,通常用于重叠类型
#import "GPUImageSourceOverBlendFilter.h"           //源混合
#import "GPUImageColorBurnBlendFilter.h"            //色彩加深混合
#import "GPUImageColorDodgeBlendFilter.h"           //色彩减淡混合
#import "GPUImageScreenBlendFilter.h"               //屏幕包裹,通常用于创建亮点和镜头眩光
#import "GPUImageExclusionBlendFilter.h"            //排除混合
#import "GPUImageDifferenceBlendFilter.h"           //差异混合,通常用于创建更多变动的颜色
#import "GPUImageSubtractBlendFilter.h"             //差值混合,通常用于创建两个图像之间的动画变暗模糊效果
#import "GPUImageHardLightBlendFilter.h"            //强光混合,通常用于创建阴影效果
#import "GPUImageSoftLightBlendFilter.h"            //柔光混合
#import "GPUImageChromaKeyBlendFilter.h"            //色度键混合
#import "GPUImageMaskFilter.h"                      //遮罩混合
#import "GPUImageHazeFilter.h"                      //朦胧加暗
#import "GPUImageLuminanceThresholdFilter.h"        //亮度阈
#import "GPUImageAdaptiveThresholdFilter.h"         //自适应阈值
#import "GPUImageAddBlendFilter.h"                  //通常用于创建两个图像之间的动画变亮模糊效果
#import "GPUImageDivideBlendFilter.h"               //通常用于创建两个图像之间的动画变暗模糊效果


#pragma mark - 尚不清楚
#import "GPUImageJFAVoroniFilter.h"
#import "GPUImageVoroniConsumerFilter.h"

// 开启硬解码
[option setPlayerOptionValue:@"1" forKey:@"videotoolbox"];

硬编码的施用场景: 大家要将主播的录像数据传送给服务器

由此摄影头来采访图像,然后将募集到的图像,通过硬编码的主意进行编码,末了编码后的多司令员其构成成H264的码流通过网络盛传。

视频头采集图像, iOS系统提供了AVCaptureSession来采访摄像头的图像数据.
项目中我是直接运用<a
href=”https://github.com/BradLarson/GPUImage"&gt; GPUImage
</a>中的GPUImageVideoCamera,
直接设置GPUImageVideoCamera的代理即可,
在其代理方法- (void)willOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer;拓展数据编码即可.

牢记一点:
不管是系统自带的AVCaptureSession还是GPUImageVideoCamera征集到的数码都是未通过编码的CM山姆pleBuffer.

下一场将采访到的多少, 用iOS开放的VideoToolbox进展硬编码.
关于VideoToolbox硬编解码网上广大科目, 当然最好是看Apple的官方文档,
假如只是硬编码, 看自己的品种即可.

着重的编码函数(来自YOLO直播负责人的开源项目<a
href=”https://github.com/Guikunzhi/BeautifyFaceDemo"&gt;
BeautifyFaceDemo </a>)

void didCompressH264(void *outputCallbackRefCon, void *sourceFrameRefCon, OSStatus status, VTEncodeInfoFlags infoFlags,
                     CMSampleBufferRef sampleBuffer )
{
    if (status != 0) return;
    // 采集的未编码数据是否准备好
    if (!CMSampleBufferDataIsReady(sampleBuffer))
    {
        NSLog(@"didCompressH264 data is not ready ");
        return;
    }
    ALinH264Encoder* encoder = (__bridge ALinH264Encoder*)outputCallbackRefCon;

    bool keyframe = !CFDictionaryContainsKey((CFArrayGetValueAtIndex(CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, true), 0)), kCMSampleAttachmentKey_NotSync);

    if (keyframe) // 关键帧
    {
        CMFormatDescriptionRef format = CMSampleBufferGetFormatDescription(sampleBuffer);
        size_t sparameterSetSize, sparameterSetCount;
        const uint8_t *sparameterSet;
        OSStatus statusCode = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(format, 0, &sparameterSet, &sparameterSetSize, &sparameterSetCount, 0 );
        if (statusCode == noErr)
        {
            size_t pparameterSetSize, pparameterSetCount;
            const uint8_t *pparameterSet;
            OSStatus statusCode = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(format, 1, &pparameterSet, &pparameterSetSize, &pparameterSetCount, 0 );
            if (statusCode == noErr)
            {
                encoder->sps = [NSData dataWithBytes:sparameterSet length:sparameterSetSize];
                encoder->pps = [NSData dataWithBytes:pparameterSet length:pparameterSetSize];
                NSLog(@"sps:%@ , pps:%@", encoder->sps, encoder->pps);
            }
        }
    }

    CMBlockBufferRef dataBuffer = CMSampleBufferGetDataBuffer(sampleBuffer);
    size_t length, totalLength;
    char *dataPointer;
    OSStatus statusCodeRet = CMBlockBufferGetDataPointer(dataBuffer, 0, &length, &totalLength, &dataPointer);
    if (statusCodeRet == noErr) {

        size_t bufferOffset = 0;
        static const int AVCCHeaderLength = 4;
        while (bufferOffset < totalLength - AVCCHeaderLength)
        {
            uint32_t NALUnitLength = 0;
            memcpy(&NALUnitLength, dataPointer + bufferOffset, AVCCHeaderLength);
            NALUnitLength = CFSwapInt32BigToHost(NALUnitLength);
            NSData *data = [[NSData alloc] initWithBytes:(dataPointer + bufferOffset + AVCCHeaderLength) length:NALUnitLength];
            bufferOffset += AVCCHeaderLength + NALUnitLength;
            NSLog(@"sendData-->> %@ %lu", data, bufferOffset);
        }

    }

}

DESKBANDINFO:

感触

即便那个项目是个山寨的, 高仿的, 可是仍旧已经很巨大了.
具体的细节依然需要我们温馨去看自己的品种源码.
短短几千字还真说不清这么多的知识点. blog的篇章名字说了是初窥,
还真的只是初窥, 录像直播里面的坑太多. 且行且珍爱…

tip: 本文理论知识部分, 采集自网络.
请记住一句话talk is cheap show me the code, 重点在于Demo品类本身.
理论部分自己只是一个挑夫和总计者…

图片 3图片 4

类型编译环境

Xcode7(及以上)
极致是将项目跑在真机上. 有些地点模拟器是不辅助的, 也看不到任何功能的,
比如硬编码/智能美颜等, 这多少个功效模块, 我做了限定的, 需要真机状态才能举行.

using System;
using System.Runtime.InteropServices;

namespace MyDiskInfo.Interop
{
    /// <summary>
    /// Receives information about a band object. This structure is used with the deprecated IDeskBand::GetBandInfo method.
    /// </summary>
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    public struct DESKBANDINFO
    {
        /// <summary>
        /// Set of flags that determine which members of this structure are being requested. 
        /// </summary>
        /// <remarks>
        /// This will be a combination of the following values:
        ///     DBIM_MINSIZE    ptMinSize is being requested.
        ///     DBIM_MAXSIZE    ptMaxSize is being requested.
        ///     DBIM_INTEGRAL   ptIntegral is being requested.
        ///     DBIM_ACTUAL     ptActual is being requested.
        ///     DBIM_TITLE      wszTitle is being requested.
        ///     DBIM_MODEFLAGS  dwModeFlags is being requested.
        ///     DBIM_BKCOLOR    crBkgnd is being requested.
        /// </remarks>
        public DBIM dwMask;

        /// <summary>
        /// Point structure that receives the minimum size of the band object. 
        /// The minimum width is placed in the x member and the minimum height 
        /// is placed in the y member. 
        /// </summary>
        public POINT ptMinSize;

        /// <summary>
        /// Point structure that receives the maximum size of the band object. 
        /// The maximum height is placed in the y member and the x member is ignored. 
        /// If there is no limit for the maximum height, (LONG)-1 should be used. 
        /// </summary>
        public POINT ptMaxSize;

        /// <summary>
        /// Point structure that receives the sizing step value of the band object. 
        /// The vertical step value is placed in the y member, and the x member is ignored. 
        /// The step value determines in what increments the band will be resized. 
        /// </summary>
        /// <remarks>
        /// This member is ignored if dwModeFlags does not contain DBIMF_VARIABLEHEIGHT. 
        /// </remarks>
        public POINT ptIntegral;

        /// <summary>
        /// Point structure that receives the ideal size of the band object. 
        /// The ideal width is placed in the x member and the ideal height is placed in the y member. 
        /// The band container will attempt to use these values, but the band is not guaranteed to be this size.
        /// </summary>
        public POINT ptActual;

        /// <summary>
        /// The title of the band.
        /// </summary>
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 255)]
        public String wszTitle;

        /// <summary>
        /// A value that receives a set of flags that define the mode of operation for the band object. 
        /// </summary>
        /// <remarks>
        /// This must be one or a combination of the following values.
        ///     DBIMF_NORMAL
        ///     The band is normal in all respects. The other mode flags modify this flag.
        ///     DBIMF_VARIABLEHEIGHT
        ///     The height of the band object can be changed. The ptIntegral member defines the 
        ///     step value by which the band object can be resized. 
        ///     DBIMF_DEBOSSED
        ///     The band object is displayed with a sunken appearance.
        ///     DBIMF_BKCOLOR
        ///     The band will be displayed with the background color specified in crBkgnd.
        /// </remarks>
        public DBIMF dwModeFlags;

        /// <summary>
        /// The background color of the band.
        /// </summary>
        /// <remarks>
        /// This member is ignored if dwModeFlags does not contain the DBIMF_BKCOLOR flag. 
        /// </remarks>
        public COLORREF crBkgnd;

        /// <summary>
        /// The view mode of the band object. This is one of the following values.
        /// </summary>
        [Flags]
        public enum DBIF
        {
            /// <summary>
            /// Band object is displayed in a horizontal band.
            /// </summary>
            DBIF_VIEWMODE_NORMAL = 0x0000,

            /// <summary>
            /// Band object is displayed in a vertical band.
            /// </summary>
            DBIF_VIEWMODE_VERTICAL = 0x0001,

            /// <summary>
            /// Band object is displayed in a floating band.
            /// </summary>
            DBIF_VIEWMODE_FLOATING = 0x0002,

            /// <summary>
            /// Band object is displayed in a transparent band.
            /// </summary>
            DBIF_VIEWMODE_TRANSPARENT = 0x0004
        }

        /// <summary>
        /// The set of flags that determine which members of this structure are being requested by the caller. One or more of the following values:
        /// </summary>
        [Flags]
        public enum DBIM
        {
            /// <summary>
            /// ptMinSize is requested.
            /// </summary>
            DBIM_MINSIZE = 0x0001,

            /// <summary>
            /// ptMaxSize is requested.
            /// </summary>
            DBIM_MAXSIZE = 0x0002,

            /// <summary>
            /// ptIntegral is requested.
            /// </summary>
            DBIM_INTEGRAL = 0x0004,

            /// <summary>
            /// ptActual is requested.
            /// </summary>
            DBIM_ACTUAL = 0x0008,

            /// <summary>
            /// wszTitle is requested.
            /// </summary>
            DBIM_TITLE = 0x0010,

            /// <summary>
            /// dwModeFlags is requested.
            /// </summary>
            DBIM_MODEFLAGS = 0x0020,

            /// <summary>
            /// crBkgnd is requested.
            /// </summary>
            DBIM_BKCOLOR = 0x0040
        }

        /// <summary>
        /// A value that receives a set of flags that specify the mode of operation for the band object. One or more of the following values:
        /// </summary>
        [Flags]
        public enum DBIMF : uint
        {
            /// <summary>
            /// The band uses default properties. The other mode flags modify this flag.
            /// </summary>
            DBIMF_NORMAL = 0x0000,

            /// <summary>
            /// Windows XP and later: The band object is of a fixed sized and position. With this flag, a sizing grip is not displayed on the band object.
            /// </summary>
            DBIMF_FIXED = 0x0001,

            /// <summary>
            /// DBIMF_FIXEDBMP
            /// Windows XP and later: The band object uses a fixed bitmap (.bmp) file as its background. Note that backgrounds are not supported in all cases, so the bitmap may not be seen even when this flag is set.
            /// </summary>
            DBIMF_FIXEDBMP = 0x0004,

            /// <summary>
            /// The height of the band object can be changed. The ptIntegral member defines the step value by which the band object can be resized.
            /// </summary>
            DBIMF_VARIABLEHEIGHT = 0x0008,

            /// <summary>
            /// Windows XP and later: The band object cannot be removed from the band container.
            /// </summary>
            DBIMF_UNDELETEABLE = 0x0010,

            /// <summary>
            /// The band object is displayed with a sunken appearance.
            /// </summary>
            DBIMF_DEBOSSED = 0x0020,

            /// <summary>
            /// The band is displayed with the background color specified in crBkgnd.
            /// </summary>
            DBIMF_BKCOLOR = 0x0040,

            /// <summary>
            /// Windows XP and later: If the full band object cannot be displayed (that is, the band object is smaller than ptActual, a chevron is shown to indicate that there are more options available. These options are displayed when the chevron is clicked.
            /// </summary>
            DBIMF_USECHEVRON = 0x0080,

            /// <summary>
            /// Windows XP and later: The band object is displayed in a new row in the band container.
            /// </summary>
            DBIMF_BREAK = 0x0100,

            /// <summary>
            /// Windows XP and later: The band object is the first object in the band container.
            /// </summary>
            DBIMF_ADDTOFRONT = 0x0200,

            /// <summary>
            /// Windows XP and later: The band object is displayed in the top row of the band container.
            /// </summary>
            DBIMF_TOPALIGN = 0x0400,

            /// <summary>
            /// Windows Vista and later: No sizing grip is ever displayed to allow the user to move or resize the band object.
            /// </summary>
            DBIMF_NOGRIPPER = 0x0800,

            /// <summary>
            /// Windows Vista and later: A sizing grip that allows the user to move or resize the band object is always shown, even if that band object is the only one in the container.
            /// </summary>
            DBIMF_ALWAYSGRIPPER = 0x1000,

            /// <summary>
            /// Windows Vista and later: The band object should not display margins.
            /// </summary>
            DBIMF_NOMARGINS = 0x2000
        }
    }
}

品种下载地址

<a
href=”https://github.com/SunLiner/MiaowShow"&gt;GitHub下载地址&lt;/a&gt;
请star和fork. 后续的bug会持续立异到github上的.
有问题得以在简书给本人留言/私信, 或者知乎(简书个人上首页有本人的果壳网)私信我.

四月9日黎明更新: 项目早就合并录像直播推流
blog地址详解<a
href=”http://www.jianshu.com/p/8ea016b2720e"&gt;快速集成iOS基于RTMP的视频推流&lt;/a&gt;

View Code

联系我

<a href=”https://github.com/SunLiner"&gt;github&lt;/a&gt;

<a
href=”http://www.weibo.com/5589163526/profile?rightmod=1&wvr=6&mod=personinfo&is\_all=1"&gt;微博&lt;/a&gt;

<a
href=”http://www.jianshu.com/users/9723687edfb5/latest\_articles"&gt;简书&lt;/a&gt;

POINT:

图片 5图片 6

// This code snippet was used by SharpShell.
//
using System.Runtime.InteropServices;

namespace MyDiskInfo.Interop
{
    /// <summary>
    /// The POINT structure defines the x- and y- coordinates of a point.
    /// </summary>
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    public struct POINT
    {
        /// <summary>
        /// The x-coordinate of the point.
        /// </summary>
        public int X;

        /// <summary>
        /// The y-coordinate of the point.
        /// </summary>
        public int Y;
    }
}

View Code

RECT:

图片 7图片 8

using System.Runtime.InteropServices;

namespace MyDiskInfo.Interop
{
    [StructLayout(LayoutKind.Sequential)]
    public struct RECT
    {
        public RECT(int left, int top, int right, int bottom)
        {
            this.left = left;
            this.top = top;
            this.right = right;
            this.bottom = bottom;
        }


        public int left, top, right, bottom;

        public int Width()
        {
            return right - left;
        }

        public int Height()
        {
            return bottom - top;
        }

        public void Offset(int x, int y)
        {
            left += x;
            right += x;
            top += y;
            bottom += y;
        }

        public void Set(int left, int top, int right, int bottom)
        {
            this.left = left;
            this.top = top;
            this.right = right;
            this.bottom = bottom;
        }

        public bool IsEmpty()
        {
            return Width() == 0 && Height() == 0;
        }
    }
}

View Code

Attributes:

图片 9图片 10

using System;
using System.Runtime.InteropServices;

namespace MyDiskInfo
{
    /// <summary>
    /// The display name of the extension and the description for the HelpText(displayed in status bar when menu command selected).
    /// </summary>
    [AttributeUsage(AttributeTargets.Class)]
    public class DeskBandInfoAttribute : System.Attribute
    {
        private string _displayName;
        private string _helpText;

        public string DisplayName
        {
            get { return _displayName; }
        }

        public string HelpText
        {
            get { return _helpText; }
        }

        public DeskBandInfoAttribute() { }

        public DeskBandInfoAttribute(string displayName, string helpText)
        {
            _displayName = displayName;
            _helpText = helpText;
        }
    }
}

View Code

ComImport:

图片 11图片 12

using System;
using System.Runtime.InteropServices;

namespace MyDiskInfo.Interop
{
    /// <summary>
    /// Provides a simple way to support communication between an object and its site in the container.
    /// </summary>
    [ComImport]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [Guid("FC4801A3-2BA9-11CF-A229-00AA003D7352")]
    public interface IObjectWithSite
    {
        /// <summary>
        /// Enables a container to pass an object a pointer to the interface for its site.
        /// </summary>
        /// <param name="pUnkSite">A pointer to the IUnknown interface pointer of the site managing this object.
        /// If NULL, the object should call Release on any existing site at which point the object no longer knows its site.</param>
        void SetSite([In, MarshalAs(UnmanagedType.IUnknown)] Object pUnkSite);

        /// <summary>
        /// Retrieves the latest site passed using SetSite.
        /// </summary>
        /// <param name="riid">The IID of the interface pointer that should be returned in ppvSite.</param>
        /// <param name="ppvSite">Address of pointer variable that receives the interface pointer requested in riid.</param>
        void GetSite(ref Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out Object ppvSite);
    }

    /// <summary>
    /// Exposes a method that is used to communicate focus changes for a user input object contained in the Shell.
    /// </summary>
    [ComImport]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [Guid("F1DB8392-7331-11D0-8C99-00A0C92DBFE8")]
    public interface IInputObjectSite
    {
        /// <summary>
        /// Informs the browser that the focus has changed.
        /// </summary>
        /// <param name="punkObj">The address of the IUnknown interface of the object gaining or losing the focus.</param>
        /// <param name="fSetFocus">Indicates if the object has gained or lost the focus. If this value is nonzero, the object has gained the focus.
        /// If this value is zero, the object has lost the focus.</param>
        /// <returns>Returns S_OK if the method was successful, or a COM-defined error code otherwise.</returns>
        [PreserveSig]
        Int32 OnFocusChangeIS([MarshalAs(UnmanagedType.IUnknown)] Object punkObj, Int32 fSetFocus);
    }

    /// <summary>
    /// The IOleWindow interface provides methods that allow an application to obtain the handle to the various windows that participate in in-place activation, and also to enter and exit context-sensitive help mode.
    /// </summary>
    [ComImport]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [Guid("00000114-0000-0000-C000-000000000046")]
    public interface IOleWindow
    {
        /// <summary>
        /// Retrieves a handle to one of the windows participating in in-place activation (frame, document, parent, or in-place object window).
        /// </summary>
        /// <param name="phwnd">A pointer to a variable that receives the window handle.</param>
        /// <returns>This method returns S_OK on success.</returns>
        [PreserveSig]
        int GetWindow(out IntPtr phwnd);

        /// <summary>
        /// Determines whether context-sensitive help mode should be entered during an in-place activation session.
        /// </summary>
        /// <param name="fEnterMode">TRUE if help mode should be entered; FALSE if it should be exited.</param>
        /// <returns>This method returns S_OK if the help mode was entered or exited successfully, depending on the value passed in fEnterMode.</returns>
        [PreserveSig]
        int ContextSensitiveHelp(bool fEnterMode);
    }

    [ComImport]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [Guid("012DD920-7B26-11D0-8CA9-00A0C92DBFE8")]
    public interface IDockingWindow : IOleWindow
    {
        #region IOleWindow

        [PreserveSig]
        new int GetWindow(out IntPtr phwnd);

        [PreserveSig]
        new int ContextSensitiveHelp(bool fEnterMode);

        #endregion

        /// <summary>
        /// Instructs the docking window object to show or hide itself.
        /// </summary>
        /// <param name="fShow">TRUE if the docking window object should show its window.
        /// FALSE if the docking window object should hide its window and return its border space by calling SetBorderSpaceDW with zero values.</param>
        /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns>
        [PreserveSig]
        int ShowDW([In] bool fShow);

        /// <summary>
        /// Notifies the docking window object that it is about to be removed from the frame.
        /// The docking window object should save any persistent information at this time.
        /// </summary>
        /// <param name="dwReserved">Reserved. This parameter should always be zero.</param>
        /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns>
        [PreserveSig]
        int CloseDW([In] UInt32 dwReserved);

        /// <summary>
        /// Notifies the docking window object that the frame's border space has changed.
        /// </summary>
        /// <param name="prcBorder">Pointer to a RECT structure that contains the frame's available border space.</param>
        /// <param name="punkToolbarSite">Pointer to the site's IUnknown interface. The docking window object should call the QueryInterface method for this interface, requesting IID_IDockingWindowSite.
        /// The docking window object then uses that interface to negotiate its border space. It is the docking window object's responsibility to release this interface when it is no longer needed.</param>
        /// <param name="fReserved">Reserved. This parameter should always be zero.</param>
        /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns>
        [PreserveSig]
        int ResizeBorderDW(RECT prcBorder, [In, MarshalAs(UnmanagedType.IUnknown)] IntPtr punkToolbarSite, bool fReserved);
    }

    /// <summary>
    /// Gets information about a band object.
    /// </summary>
    [ComImport]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [Guid("EB0FE172-1A3A-11D0-89B3-00A0C90A90AC")]
    public interface IDeskBand : IDockingWindow
    {
        #region IOleWindow

        [PreserveSig]
        new int GetWindow(out IntPtr phwnd);

        [PreserveSig]
        new int ContextSensitiveHelp(bool fEnterMode);

        #endregion

        #region IDockingWindow

        [PreserveSig]
        new int ShowDW([In] bool fShow);

        [PreserveSig]
        new int CloseDW([In] UInt32 dwReserved);

        [PreserveSig]
        new int ResizeBorderDW(RECT prcBorder, [In, MarshalAs(UnmanagedType.IUnknown)] IntPtr punkToolbarSite, bool fReserved);

        #endregion

        /// <summary>
        /// Gets state information for a band object.
        /// </summary>
        /// <param name="dwBandID">The identifier of the band, assigned by the container. The band object can retain this value if it is required.</param>
        /// <param name="dwViewMode">The view mode of the band object. One of the following values: DBIF_VIEWMODE_NORMAL, DBIF_VIEWMODE_VERTICAL, DBIF_VIEWMODE_FLOATING, DBIF_VIEWMODE_TRANSPARENT.</param>
        /// <param name="pdbi">Pointer to a DESKBANDINFO structure that receives the band information for the object. The dwMask member of this structure indicates the specific information that is being requested.</param>
        /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns>
        [PreserveSig]
        int GetBandInfo(UInt32 dwBandID, DESKBANDINFO.DBIF dwViewMode, ref DESKBANDINFO pdbi);
    }

    /// <summary>
    /// Exposes methods to enable and query translucency effects in a deskband object.
    /// </summary>
    [ComImport]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [Guid("79D16DE4-ABEE-4021-8D9D-9169B261D657")]
    public interface IDeskBand2 : IDeskBand
    {
        #region IOleWindow

        [PreserveSig]
        new int GetWindow(out IntPtr phwnd);

        [PreserveSig]
        new int ContextSensitiveHelp(bool fEnterMode);

        #endregion

        #region IDockingWindow

        [PreserveSig]
        new int ShowDW([In] bool fShow);

        [PreserveSig]
        new int CloseDW([In] UInt32 dwReserved);

        [PreserveSig]
        new int ResizeBorderDW(RECT prcBorder, [In, MarshalAs(UnmanagedType.IUnknown)] IntPtr punkToolbarSite, bool fReserved);

        #endregion

        #region IDeskBand

        [PreserveSig]
        new int GetBandInfo(UInt32 dwBandID, DESKBANDINFO.DBIF dwViewMode, ref DESKBANDINFO pdbi);

        #endregion

        /// <summary>
        /// Indicates the deskband's ability to be displayed as translucent.
        /// </summary>
        /// <param name="pfCanRenderComposited">When this method returns, contains a BOOL indicating ability.</param>
        /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns>
        [PreserveSig]
        int CanRenderComposited(out bool pfCanRenderComposited);

        /// <summary>
        /// Sets the composition state.
        /// </summary>
        /// <param name="fCompositionEnabled">TRUE to enable the composition state; otherwise, FALSE.</param>
        /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns>
        [PreserveSig]
        int SetCompositionState(bool fCompositionEnabled);

        /// <summary>
        /// Gets the composition state.
        /// </summary>
        /// <param name="pfCompositionEnabled">When this method returns, contains a BOOL that indicates state.</param>
        /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns>
        [PreserveSig]
        int GetCompositionState(out bool pfCompositionEnabled);
    }
}

View Code

DeskBand,这里和GitHub上的次序不同的是,DeskBand直接接轨的ElementHost类,GitHub上的类似是多例的,我想要的是单例的,所以修改了弹指间。这里粘的代码是WPF的,倘若您想实现Winform的,就让DeskBand继承UserControl,DeskBand代码如下:

图片 13图片 14

// Copyright(c) 2017 Patrick Becker
//
// Visit the Project page for more information.
// https://github.com/patbec/TaskbarSampleExtension


using Microsoft.Win32;
using System;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using MyDiskInfo.Interop;
using System.Windows.Forms.Integration;

namespace MyDiskInfo
{
    /// <summary>
    /// Basic class for a DeskBand object
    /// </summary>
    /// <example>
    /// [ComVisible(true)]
    /// [Guid("00000000-0000-0000-0000-000000000000")]
    /// [DeskBandInfo("Beispiel Erweiterung", "Diese ist eine Beispiel Erweiterung für die Taskleiste.")]
    /// public class SampleExtension : DeskBand
    /// { /*...*/ }
    /// </example>
    public class DeskBand : ElementHost, IObjectWithSite, IDeskBand2
    {

        private const int S_OK = 0;
        private const int E_NOTIMPL = unchecked((int)0x80004001);

        protected IInputObjectSite DeskBandSite;

        public DeskBand()
        {
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            this.Name = "DeskBand";
        }

        #region Properties

        /// <summary>
        /// Title of the band object, displayed by default on the left or top of the object.
        /// </summary>
        [Browsable(true)]
        [DefaultValue("")]
        public String Title { get; set; }

        /// <summary>
        /// Minimum size of the band object. Default value of -1 sets no minimum constraint.
        /// </summary>
        [Browsable(true)]
        [DefaultValue(typeof(Size), "-1,-1")]
        public Size MinSize { get; set; }

        /// <summary>
        /// Maximum size of the band object. Default value of -1 sets no maximum constraint.
        /// </summary>
        [Browsable(true)]
        [DefaultValue(typeof(Size), "-1,-1")]
        public Size MaxSize { get; set; }

        /// <summary>
        /// Minimum vertical size of the band object. Default value of -1 sets no maximum constraint. (Used when the taskbar is aligned vertically.)
        /// </summary>
        [Browsable(true)]
        [DefaultValue(typeof(Size), "-1,-1")]
        public Size MinSizeVertical { get; set; }

        /// <summary>
        /// Says that band object's size must be multiple of this size. Defauilt value of -1 does not set this constraint.
        /// </summary>
        [Browsable(true)]
        [DefaultValue(typeof(Size), "-1,-1")]
        public Size IntegralSize { get; set; }

        #endregion

        #region IObjectWithSite

        public void SetSite([In, MarshalAs(UnmanagedType.IUnknown)] Object pUnkSite)
        {
            if (DeskBandSite != null)
                Marshal.ReleaseComObject(DeskBandSite);

            DeskBandSite = (IInputObjectSite)pUnkSite;
        }

        public void GetSite(ref Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out Object ppvSite)
        {
            ppvSite = DeskBandSite;
        }

        #endregion

        #region IDeskBand2

        public virtual int CanRenderComposited(out bool pfCanRenderComposited)
        {
            pfCanRenderComposited = true;
            return S_OK;
        }

        public int SetCompositionState(bool fCompositionEnabled)
        {
            fCompositionEnabled = true;
            return S_OK;
        }

        public int GetCompositionState(out bool pfCompositionEnabled)
        {
            pfCompositionEnabled = false;
            return S_OK;
        }

        public int GetBandInfo(uint dwBandID, DESKBANDINFO.DBIF dwViewMode, ref DESKBANDINFO pdbi)
        {
            if (pdbi.dwMask.HasFlag(DESKBANDINFO.DBIM.DBIM_MINSIZE))
            {
                // Support for a vertical taskbar
                // Most examples have no support for a vertical taskbar. Who in hell uses their taskbar vertically? Me! Very practical on a 21:9 monitor.
                if (dwViewMode.HasFlag(DESKBANDINFO.DBIF.DBIF_VIEWMODE_FLOATING) || dwViewMode.HasFlag(DESKBANDINFO.DBIF.DBIF_VIEWMODE_VERTICAL))
                {
                    pdbi.ptMinSize.Y = this.MinSizeVertical.Width;
                    pdbi.ptMinSize.X = this.MinSizeVertical.Height;
                }
                else
                {
                    pdbi.ptMinSize.X = this.MinSize.Width;
                    pdbi.ptMinSize.Y = this.MinSize.Height;
                }
            }
            if (pdbi.dwMask.HasFlag(DESKBANDINFO.DBIM.DBIM_MAXSIZE))
            {
                if (dwViewMode.HasFlag(DESKBANDINFO.DBIF.DBIF_VIEWMODE_FLOATING) || dwViewMode.HasFlag(DESKBANDINFO.DBIF.DBIF_VIEWMODE_VERTICAL))
                {
                    pdbi.ptMaxSize.Y = this.MaxSize.Width;
                    pdbi.ptMaxSize.X = this.MaxSize.Height;
                }
                else
                {
                    pdbi.ptMaxSize.X = this.MaxSize.Width;
                    pdbi.ptMaxSize.Y = this.MaxSize.Height;
                }
            }
            if (pdbi.dwMask.HasFlag(DESKBANDINFO.DBIM.DBIM_INTEGRAL))
            {
                if (dwViewMode.HasFlag(DESKBANDINFO.DBIF.DBIF_VIEWMODE_FLOATING) || dwViewMode.HasFlag(DESKBANDINFO.DBIF.DBIF_VIEWMODE_VERTICAL))
                {
                    pdbi.ptIntegral.Y = this.IntegralSize.Width;
                    pdbi.ptIntegral.X = this.IntegralSize.Height;
                }
                else
                {
                    pdbi.ptIntegral.X = this.IntegralSize.Width;
                    pdbi.ptIntegral.Y = this.IntegralSize.Height;
                }
            }

            if (pdbi.dwMask.HasFlag(DESKBANDINFO.DBIM.DBIM_ACTUAL))
            {
                if (dwViewMode.HasFlag(DESKBANDINFO.DBIF.DBIF_VIEWMODE_FLOATING) || dwViewMode.HasFlag(DESKBANDINFO.DBIF.DBIF_VIEWMODE_VERTICAL))
                {
                    pdbi.ptActual.Y = this.Size.Width;
                    pdbi.ptActual.X = this.Size.Height;
                }
                else
                {
                    pdbi.ptActual.X = this.Size.Width;
                    pdbi.ptActual.Y = this.Size.Height;
                }
            }

            if (pdbi.dwMask.HasFlag(DESKBANDINFO.DBIM.DBIM_TITLE))
            {
                pdbi.wszTitle = this.Title;
            }

            pdbi.dwModeFlags = DESKBANDINFO.DBIMF.DBIMF_ALWAYSGRIPPER | DESKBANDINFO.DBIMF.DBIMF_NORMAL | DESKBANDINFO.DBIMF.DBIMF_VARIABLEHEIGHT;
            pdbi.dwMask = pdbi.dwMask | DESKBANDINFO.DBIM.DBIM_BKCOLOR | DESKBANDINFO.DBIM.DBIM_TITLE; // Testen

            return S_OK;
        }

        public int GetWindow(out IntPtr phwnd)
        {
            phwnd = Handle;
            return S_OK;
        }

        public int ContextSensitiveHelp(bool fEnterMode)
        {
            return S_OK;
        }

        public int ShowDW([In] bool fShow)
        {
            if (fShow)
                Show();
            else
                Hide();

            return S_OK;
        }

        public virtual void ClearResources()
        {
        }

        public int CloseDW([In] uint dwReserved)
        {
            ClearResources();
            Dispose(true);
            return S_OK;
        }

        public int ResizeBorderDW(RECT prcBorder, [In, MarshalAs(UnmanagedType.IUnknown)] IntPtr punkToolbarSite, bool fReserved)
        {
            return E_NOTIMPL;
        }

        #endregion

        #region Register / Unregister

        [ComRegisterFunctionAttribute]
        public static void Register(Type t)
        {
            string guid = t.GUID.ToString("B");

            DeskBandInfoAttribute[] deskBandInfo = (DeskBandInfoAttribute[])
            t.GetCustomAttributes(typeof(DeskBandInfoAttribute), false);

            // Register only the extension if the attribute DeskBandInfo is used.
            if (deskBandInfo.Length == 1)
            {
                RegistryKey rkClass = Registry.ClassesRoot.CreateSubKey(@"CLSID\" + guid);
                RegistryKey rkCat = rkClass.CreateSubKey("Implemented Categories");

                string _displayName = t.Name;
                string _helpText = t.Name;


                if (deskBandInfo[0].DisplayName != null)
                {
                    _displayName = deskBandInfo[0].DisplayName;
                }

                if (deskBandInfo[0].HelpText != null)
                {
                    _helpText = deskBandInfo[0].HelpText;
                }

                rkClass.SetValue(null, _displayName);
                rkClass.SetValue("MenuText", _displayName);
                rkClass.SetValue("HelpText", _helpText);

                // TaskBar
                rkCat.CreateSubKey("{00021492-0000-0000-C000-000000000046}");

                Console.WriteLine(String.Format("{0} {1} {2}", guid, _displayName, "successfully registered."));
            }
            else
            {
                Console.WriteLine(guid + " has no attributes");
            }
        }

        [ComUnregisterFunctionAttribute]
        public static void Unregister(Type t)
        {
            string guid = t.GUID.ToString("B");

            DeskBandInfoAttribute[] deskBandInfo = (DeskBandInfoAttribute[])
            t.GetCustomAttributes(typeof(DeskBandInfoAttribute), false);

            if (deskBandInfo.Length == 1)
            {
                string _displayName = t.Name;

                if (deskBandInfo[0].DisplayName != null)
                {
                    _displayName = deskBandInfo[0].DisplayName;
                }

                Registry.ClassesRoot.CreateSubKey(@"CLSID").DeleteSubKeyTree(guid);

                Console.WriteLine(String.Format("{0} {1} {2}", guid, _displayName, "successfully removed."));
            }
            else
            {
                Console.WriteLine(guid + " has no attributes");
            }
        }

        #endregion
    }
}

View Code

DiskInfo,该类继承DeskBand,用于落实工作和界面,代码如下:

图片 15图片 16

using DataStruct;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WCFServer;

namespace MyDiskInfo
{
    /// <summary>
    /// 固态硬盘信息显示控件
    /// </summary>
    public partial class DiskInfoCtrl : UserControl
    {
        #region 字段
        private Thread _thread = null;
        private IClientServer _client = new ClientServer();
        private double _width = 140;
        private double _height = 30;
        private int _interval = 60 * 1000; //刷新间隔
        private DiskModel _diskInfo = null;
        private DiskInfoViewModel _model = new DiskInfoViewModel();
        #endregion

        #region 构造函数
        public DiskInfoCtrl()
        {
            InitializeComponent();

            //尺寸
            this.Width = _width;
            this.Height = _height;

            this.DataContext = _model;

            ShowDiskInfo();

            _thread = new Thread(new ThreadStart(() =>
            {
                while (true)
                {
                    Thread.Sleep(_interval);

                    ShowDiskInfo();
                }
            }));
            _thread.Start();
        }
        #endregion

        #region 显示硬盘信息
        /// <summary>
        /// 显示硬盘信息
        /// </summary>
        private void ShowDiskInfo()
        {
            BackWork.Run(() =>
            {
                _diskInfo = _client.GetDiskInfo();
            }, () =>
            {
                _model.Info = string.Format("{0}G {1}G {2}PE", _diskInfo.LBA_TodayWrite, _diskInfo.LBA_Write, _diskInfo.PE);
            }, (ex) => { });
        }
        #endregion

        #region 释放资源
        public void ClearResources()
        {
            if (_thread != null)
            {
                _thread.Abort();
                _thread = null;
            }
        }
        #endregion

    }

    #region DiskInfoViewModel
    public class DiskInfoViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private string _Info;
        public string Info
        {
            get { return _Info; }
            set
            {
                _Info = value;
                OnPropertyChanged("Info");
            }
        }

        public void OnPropertyChanged(string name)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
        }
    }
    #endregion

}

View Code

实现工作界面的WPF用户控件:

XAML:

图片 17图片 18

<UserControl x:Class="MyDiskInfo.DiskInfoCtrl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="30" d:DesignWidth="120" >
    <Grid>
        <TextBlock Text="{Binding Info}" FontFamily="微软雅黑" FontSize="12" Foreground="White" TextAlignment="Center" HorizontalAlignment="Center" VerticalAlignment="Center"></TextBlock>
    </Grid>
</UserControl>

View Code

后台代码:

图片 19图片 20

using DataStruct;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WCFServer;

namespace MyDiskInfo
{
    /// <summary>
    /// 固态硬盘信息显示控件
    /// </summary>
    public partial class DiskInfoCtrl : UserControl
    {
        #region 字段
        private Thread _thread = null;
        private IClientServer _client = new ClientServer();
        private double _width = 140;
        private double _height = 30;
        private int _interval = 60 * 1000; //刷新间隔
        private DiskModel _diskInfo = null;
        private DiskInfoViewModel _model = new DiskInfoViewModel();
        #endregion

        #region 构造函数
        public DiskInfoCtrl()
        {
            InitializeComponent();

            //尺寸
            this.Width = _width;
            this.Height = _height;

            _diskInfo = _client.GetDiskInfo();
            _model.Info = string.Format("{0}G {1}G {2}PE", _diskInfo.LBA_TodayWrite, _diskInfo.LBA_Write, _diskInfo.PE);
            this.DataContext = _model;

            _thread = new Thread(new ThreadStart(() =>
            {
                while (true)
                {
                    Thread.Sleep(_interval);

                    BackWork.Run(() =>
                    {
                        _diskInfo = _client.GetDiskInfo();
                    }, () =>
                    {
                        _model.Info = string.Format("{0}G {1}G {2}PE", _diskInfo.LBA_TodayWrite, _diskInfo.LBA_Write, _diskInfo.PE);
                    }, (ex) => { });
                }
            }));
            _thread.Start();
        }
        #endregion

        #region 释放资源
        public void ClearResources()
        {
            if (_thread != null)
            {
                _thread.Abort();
                _thread = null;
            }
        }
        #endregion

    }

    #region DiskInfoViewModel
    public class DiskInfoViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private string _Info;
        public string Info
        {
            get { return _Info; }
            set
            {
                _Info = value;
                OnPropertyChanged("Info");
            }
        }

        public void OnPropertyChanged(string name)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
        }
    }
    #endregion

}

View Code

    类库是急需签字的:

图片 21

其他代码就不粘了,下边粘的代码,去掉业务代码,写个测试的界面,也可以跑起来,程序写好后,怎么设置呢,我写了个Install.bat代码如下:

图片 22图片 23

@echo off

"%~dp0gacutil.exe" /if "%~dp0MyDiskInfo.dll"
"%~dp0RegAsm.exe" "%~dp0MyDiskInfo.dll"
reg import "%~dp0register.reg"

"%~dp0ServiceInstallUtil\InstallUtil.exe" "%~dp0MyDiskInfoService.exe"
sc config MyDiskInfoService start= auto
sc config MyDiskInfoService type= interact type= own
net start MyDiskInfoService

taskkill /f /im explorer.exe 
start explorer.exe 

Pause

View Code

自身是Win10系统,由于GitHub上的,安装之后DeskBand并没有显得在Windows工具栏菜单中,可能是注册表写的岗位不对,我写了个register.reg,代码如下:

图片 24图片 25

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\CLSID\{C7B92F87-7E59-467F-A6FF-9518DADA1C2C}]
@="DiskInfo"
"MenuText"="DiskInfo"
"HelpText"="Show DiskInfo"

[HKEY_CLASSES_ROOT\CLSID\{C7B92F87-7E59-467F-A6FF-9518DADA1C2C}\Implemented Categories]

[HKEY_CLASSES_ROOT\CLSID\{C7B92F87-7E59-467F-A6FF-9518DADA1C2C}\Implemented Categories\{00021492-0000-0000-C000-000000000046}]

[HKEY_CLASSES_ROOT\CLSID\{C7B92F87-7E59-467F-A6FF-9518DADA1C2C}\Implemented Categories\{62C8FE65-4EBB-45e7-B440-6E39B2CDBF29}]

[HKEY_CLASSES_ROOT\CLSID\{C7B92F87-7E59-467F-A6FF-9518DADA1C2C}\InprocServer32]
@="mscoree.dll"
"ThreadingModel"="Both"
"Class"="MyDiskInfo.DiskInfo"
"Assembly"="MyDiskInfo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bec8b29cd4c20aff"
"RuntimeVersion"="v4.0.30319"

[HKEY_CLASSES_ROOT\CLSID\{C7B92F87-7E59-467F-A6FF-9518DADA1C2C}\InprocServer32\1.0.0.0]
"Class"="MyDiskInfo.DiskInfo"
"Assembly"="MyDiskInfo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bec8b29cd4c20aff"
"RuntimeVersion"="v4.0.30319"

[HKEY_CLASSES_ROOT\CLSID\{C7B92F87-7E59-467F-A6FF-9518DADA1C2C}\ProgId]
@="MyDiskInfo.DiskInfo"

View Code

末段效果图:

图片 26

   
存在的题材:Win10系统下健康,Win7操作系统下,背景无法透明,要是DeskBand修改为后续Form并且安装TransparenceKey属性为BackColor,依旧无法实现透明,最终放任了。

   
由于DeskBand没有权力读取固态硬盘消息,我写了个Windows服务来读裁撤息,Windows服务的安全性设置为“这是一点一滴可信的应用程序”,使用WCF实现进程间管道通信来把数据传给DeskBand显示。

   
Windows服务注册为开机启动,不过DeskBand不是开机启动,需要协调勾选能才显得出来,DeskBand的机关启动我从未落实,网上资料多是C++的,用勾子实现。

总体代码如下:

MyDiskInfo_WPF版_固态硬盘写入量消息放到任务栏工具栏