实例介绍
【实例简介】根据迁安深蓝技术公司(萤石云网站提供),定制开发的摄像头自动截图和ftp上传图片
【实例截图】
【核心代码】
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Newtonsoft.Json.Linq;
using System.Net;
using System.Threading;
using System.Configuration;
using System.IO;
using EnterpriseDT.Net.Ftp;
namespace ys000
{
public partial class PlayMainWindow : Form
{
#region 窗口初始化,参数对象初始化
int a = 0;//记录用户是否正在播放状态,0为未播放,1为正在播放
string jsonstr = "";//摄像头列表json
string cameraid = "";//摄像头id
string cameraid2 = "";//存放全屏播放的摄像头id
string statu = "";//摄像头是否加密,1为加密,0为未加密
int c = 1;//表示用户选择的是几个窗口播放,默认为1
PictureBox[] picbox = new PictureBox[9];//创建对象数组,存放picbox对象,最多9画面,所以最多9个
private static IntPtr[] handle = new IntPtr[9];//存放播放句柄
private string[] cameraid1 = new string[9];//存放cameraid
IntPtr[] SessionId = new IntPtr[9];//存放申请的session
int j = 0;
int d = 0;
public PlayMainWindow()
{
InitializeComponent();
HkAction.MainForm = this;
try
{
HkAction.Start();//进入系统自动初始化库
}
catch (Exception ex)//出现异常则提示
{
MessageBox.Show("异常!" ex.ToString(), "提示", MessageBoxButtons.OK);
}
}
#endregion
#region 开始播放9画面
private void Start_Play9()
{
SessionId[j] = HkAction.AllocSession();//每次点击存放session
if (SessionId[j] != null)//每次播放申请会话
{
bool[] play = new bool[9];
try
{
if (a == 0)
{
play[j] = HkAction.Play(handle[0], cameraid1[j], SessionId[j]);
}
else
{
switch (j)
{
case 0:
play[j] = HkAction.Play(handle[0], cameraid1[j], SessionId[j]); break;//开始播放cameraid和handle一一对应
case 1:
play[j] = HkAction.Play(handle[1], cameraid1[j], SessionId[j]); break;
case 2:
play[j] = HkAction.Play(handle[2], cameraid1[j], SessionId[j]); break;
case 3:
play[j] = HkAction.Play(handle[3], cameraid1[j], SessionId[j]); break;
case 4:
play[j] = HkAction.Play(handle[4], cameraid1[j], SessionId[j]); break;
case 5:
play[j] = HkAction.Play(handle[5], cameraid1[j], SessionId[j]); break;
case 6:
play[j] = HkAction.Play(handle[6], cameraid1[j], SessionId[j]); break;
case 7:
play[j] = HkAction.Play(handle[7], cameraid1[j], SessionId[j]); break;
case 8:
play[j] = HkAction.Play(handle[8], cameraid1[j], SessionId[j]); break;
default:
break;
}
}
}
catch (Exception ex)
{
MessageBox.Show("异常:" ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
{
MessageBox.Show("申请会话异常!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
a = 1;
}
#endregion
#region 开始播放4画面
private void Start_Play4()
{
SessionId[j] = HkAction.AllocSession();//每次点击存放session
if (SessionId[j] != null)//每次播放申请会话
{
bool[] play = new bool[4];
try
{
if (a == 0)
{
play[j] = HkAction.Play(handle[0], cameraid1[j], SessionId[j]);
}
else
{
switch (j)
{
case 0:
play[j] = HkAction.Play(handle[0], cameraid1[j], SessionId[j]); break;//开始播放cameraid和handle一一对应
case 1:
play[j] = HkAction.Play(handle[1], cameraid1[j], SessionId[j]); break;
case 2:
play[j] = HkAction.Play(handle[2], cameraid1[j], SessionId[j]); break;
case 3:
play[j] = HkAction.Play(handle[3], cameraid1[j], SessionId[j]); break;
default:
break;
}
}
}
catch (Exception ex)
{
MessageBox.Show("异常:" ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
{
MessageBox.Show("申请会话异常!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
a = 1;
}
#endregion
#region 开始播放单画面
private void Start_Play1()
{
SessionId[j] = HkAction.AllocSession();//每次点击存放session
if (SessionId[j] != null)//每次播放申请会话
{
bool play;
try
{
play = HkAction.Play(handle[0], cameraid1[j], SessionId[j]);
if (play == true)
{
a = 1;
}
}
catch (Exception ex)
{
MessageBox.Show("异常:" ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
{
MessageBox.Show("申请会话异常!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
#endregion
#region 用户选择保存截图路径
//选择保存路径
private string ShowSaveFileDialog(string time)
{
string path1 = "";
SaveFileDialog sfd = new SaveFileDialog();
sfd.RestoreDirectory = true;//保存对话框是否记忆上次打开的目录
if (sfd.ShowDialog() == DialogResult.OK)//点了保存按钮进入
{
path1 = sfd.FileName.ToString(); //获得文件路径
return path1;
}
else
{
return null;
}
}
#endregion
#region 截图按钮
//截图按钮
private void btnCapt_Click(object sender, EventArgs e)
{
string time = DateTime.Now.ToString("yyyyMMddHHmmss"); //取系统时间
if (a == 1)
{
string path1 = ShowSaveFileDialog(time);//获取用户选择路径
if (path1 == null)
{
MessageBox.Show("截图取消", "提示", MessageBoxButtons.OK);
return;
}
string path = path1 "-" time ".jpg";//保存路径和文件名(用户选择路径)
//string path = @"C:\Users\Administrator\Downloads\" time ".jpg";//指定路径
if (HkAction.CapturePicture(path))//调用SDK截图方法
{
MessageBox.Show("截图成功,保存在:" path, "提示", MessageBoxButtons.OK);
}
else
{
MessageBox.Show("截图失败", "提示", MessageBoxButtons.OK);
}
}
else
{
MessageBox.Show("请先点击“开始”按钮!", "提示", MessageBoxButtons.OK);
}
}
#endregion
#region 停止播放按钮
//停止播放按钮
private void btnStop_Click(object sender, EventArgs e)
{
for (int g = 0; g <= j; g )
{
HkAction.Stop(SessionId[g]);
}
Array.Clear(cameraid1, 0, cameraid1.Length);
Array.Clear(SessionId, 0, SessionId.Length);
Array.Clear(handle, 0, handle.Length);
Array.Clear(picbox, 0, picbox.Length);
createBox();
j = 0;
a = 0;
}
#endregion
#region 停止播放方法
private void stopPlay()
{
for (int g = 0; g <= j; g )
{
HkAction.Stop(SessionId[g]);
}
Array.Clear(cameraid1, 0, cameraid1.Length);
Array.Clear(SessionId, 0, SessionId.Length);
Array.Clear(handle, 0, handle.Length);
Array.Clear(picbox, 0, picbox.Length);
createBox();
j = 0;
a = 0;
}
#endregion
#region 登录按钮
//登录按钮
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
if (HkAction.GetAccessToken() != null)
{
MessageBox.Show("用户登录成功!", "提示", MessageBoxButtons.OK);
label222.Text = "已登录";
}
}
catch (Exception ex)
{
MessageBox.Show("异常!" ex.ToString(), "提示", MessageBoxButtons.OK);
}
}
#endregion
#region 退出系统
//退出系统
private void btnClose_Click(object sender, EventArgs e)
{
stopall();//停止播放
HkAction.Close();//反初始化库
if (ThreadGetImage != null)
{
ThreadGetImage.Abort();
ThreadGetImage = null;
}
this.Close();
}
#endregion
#region 设备列表按钮
private void btnGetlist_Click(object sender, EventArgs e)
{
this.flowLayoutPanel2.Controls.Clear();
try
{
string getList = HkAction.playList();
jsonstr = getList;
jsonHandle(jsonstr);
}
catch (Exception ex)//出现异常则提示
{
//MessageBox.Show("异常!" ex.ToString(), "提示", MessageBoxButtons.OK);
}
}
#endregion
#region 构造实体类
public class json
{
public int resultCode { get; set; }
public int count { get; set; }
public List<cameraList> carameList { get; set; }
}
public class cameraList
{
public string cameraId { get; set; }
public string cameraName { get; set; }
public int cameraNo { get; set; }
public int defence { get; set; }
public string deviceId { get; set; }
public string deviceName { get; set; }
public int deviceSerial { get; set; }
public int isEncrypt { get; set; }
public int isShared { get; set; }
public string picUrl { get; set; }
public int status { get; set; }
public int videoLevel { get; set; }
}
public class frm//窗体实体类,用来保存全局变量,并在静态方法中调用
{
public int a { get; set; }//记录用户点击的是第几个摄像头
public int b { get; set; }//记录用户是否正在播放状态,0为未播放,1为正在播放
public int c { get; set; }//表示用户选择的是几个窗口播放,默认为1
public string jsonstr { get; set; }//摄像头列表json
public string cameraid { get; set; }//摄像头id
public string safeKey { get; set; }//摄像头密码,默认ABCDEF
}
public static JObject jObjInfo { get; set; }
public static int isOpertion { get; set; }//0未执行 1正在执行 2已经执行
public static MessageType mType { get; set; }
public enum MessageType
{
INS_PLAY_EXCEPTION = 0, // 播放异常,通常是设备断线或网络异常造成
INS_PLAY_RECONNECT = 1, // 重连,实时流播放时内部会自动重连
INS_PLAY_RECONNECT_EXCEPTION = 2, // 重连异常
INS_PLAY_START = 3, // 播放开始
INS_PLAY_STOP = 4, // 播放终止
INS_PLAY_ARCHIVE_END = 5, // 播放结束,回放结束时会有此消息
INS_RECORD_FILE = 20, // 查询的录像文件(录像搜索结果)
INS_RECORD_SEARCH_END = 21, // 录像查询结束(暂不使用)
INS_RECORD_SEARCH_FAILED = 22, // 录像查询失败
}
#endregion
#region 处理json方法,获取设备列表以缩略图显示并显示摄像头一些信息
public void jsonHandle(string str)
{
string jsonStr = str;
JObject jsonObj = JObject.Parse(jsonStr);
JArray jar = JArray.Parse(jsonObj["cameraList"].ToString());
int a = Int32.Parse(jsonObj["count"].ToString());
for (int m = 0; m < a; m )
{
JObject j = JObject.Parse(jar[m].ToString());//取第几个摄像头信息放入对象j
string picurl = j["picUrl"].ToString();//取出缩略图url
Label label1 = new Label();
label1.Text = j["cameraName"].ToString();//取出摄像头名字
Label label2 = new Label();
string isEncrypt = j["isEncrypt"].ToString();//取出摄像头状态
if (isEncrypt == "0")
{
label2.Text = "加密状态:未加密";//把摄像头加密状态给label
}
else if (isEncrypt == "1")
{
label2.Text = "加密状态:已加密";//把摄像头加密状态给label
}
string status = j["status"].ToString();
Label label3 = new Label();
if (status == "0")
{
label3.Text = "状态:离线";//把摄像头状态给label
}
else
{
label3.Text = "状态:在线";//把摄像头状态给label
}
PictureBox picbox = new PictureBox();
picbox.Size = new Size(120, 120);
picbox.Name = picbox m.ToString();//根据i值来取名
picbox.BackgroundImage = Image.FromStream(WebRequest.Create(picurl).GetResponse().GetResponseStream());//取网络图片
picbox.BackgroundImageLayout = ImageLayout.Stretch;//背景图自适应控件大小
this.flowLayoutPanel2.Controls.Add(picbox);//添加控件picturebox
this.flowLayoutPanel2.Controls.Add(label1);//添加控件label
this.flowLayoutPanel2.Controls.Add(label2);//添加控件label
this.flowLayoutPanel2.Controls.Add(label3);//添加控件label
picbox.MouseClick = new MouseEventHandler(picbox_MouseClick);//添加鼠标点击事件,方便后面确定点击的是哪个摄像头
picbox.MouseHover = new System.EventHandler(picbox_MouseHover);
picbox.MouseLeave = new System.EventHandler(picbox_MouseLeave);
//picbox.SizeModeChanged = new System.EventHandler(picbox_SizeModeChanged);
}
foreach (Control c in flowLayoutPanel2.Controls)
c.Margin = new Padding(5);
}
#endregion
#region 处理json方法重载(无参数),获取用户摄像头总数
public int jsonHandle()
{
JObject jsonObj = JObject.Parse(jsonstr);
JArray jar = JArray.Parse(jsonObj["cameraList"].ToString());
int a = Int32.Parse(jsonObj["count"].ToString());
return a;
}
#endregion
#region 处理json方法重载( 1),获取用户摄像头id
public string jsonHandle(int n)
{
JObject jsonObj = JObject.Parse(jsonstr);
JArray jar = JArray.Parse(jsonObj["cameraList"].ToString());
JObject j = JObject.Parse(jar[n].ToString());//取第几个摄像头信息放入对象j
cameraid = j["cameraId"].ToString();//取出
// Local_sessionid
// //通讯会话
//string Local_sessionid = "";
//摄像头ID
string Local_Cameraid = cameraid;
//摄像头通道号
Local_cameraNO = Convert.ToInt32(j["cameraNo"].ToString().Trim());
return cameraid;
}
#endregion
#region 处理json方法重载( 2),获取用户摄像头加密状态
public string jsonHandle1(int n)
{
JObject jsonObj = JObject.Parse(jsonstr);
JArray jar = JArray.Parse(jsonObj["cameraList"].ToString());
JObject j = JObject.Parse(jar[n].ToString());//取第几个摄像头信息放入对象j
statu = j["isEncrypt"].ToString();//取出
return statu;
}
#endregion
#region 单击该缩略图获取摄像头ID并播放
private void picbox_MouseClick(object sender, MouseEventArgs e)
{
PictureBox picb1 = sender as PictureBox;//取出点击的控件sender
string name = "";
if (picb1 != null)//点击则非空,否则为空
{
name = picb1.Name.Substring(picb1.Name.Length - 1, 1); //取名字中最后一个字,它正好是控件的index
}
int n = Int32.Parse(name);//string 转换int
cameraid = jsonHandle(n);//取出该摄像头id
if (a == 1 && c != 1)
{
for (int t = 0; t < 9; t )
{
if (cameraid == cameraid1[t])//检查视频是否已在播放中
{
MessageBox.Show("该视频已经在播放中,请勿重复点击!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
}
}
cameraid1[j] = cameraid;
statu = jsonHandle1(n);
if (statu == "1")//视频已加密,需要调用萤石接口发送短信验证码
{
MessageBox.Show("该视频已加密,暂时不能播放!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
//return;
}
else//status=="1"即未加密
{
Local_sessionid = SessionId[j].ToString();
if (c == 1)//单画面
{
handle[0] = picbox[0].Handle;
if (a == 1)
{
bool close = HkAction.Stop(SessionId[j]);
}
Start_Play1();
j = 0;
}
else if (c == 4)//4画面
{
handle[j] = picbox[j].Handle;
if (a == 1 && d == 1)
{
bool close = HkAction.Stop(SessionId[j]);
}
Start_Play4();
if (j < 3)
{
j ;
}
else if (j == 3)
{
j = 0;
d = 1;
}
}
else if (c == 9)//9画面
{
//picbox[j].Image = Image.FromFile("60.gif");//未成功播放前显示加载动态图
//picbox[j].SizeMode = PictureBoxSizeMode.CenterImage;//图片居中
handle[j] = picbox[j].Handle;//赋予句柄
if (a == 1 && d == 1)//全部容器都在播放
{
bool close = HkAction.Stop(SessionId[j]);//关闭最开始打开的画面
}
Start_Play9();
if (j < 8)
{
j ;
}
else if (j == 8)
{
j = 0;
d = 1;
}
}
}
}
#endregion
private static string AppKey = ConfigurationManager.AppSettings["AppKey"].ToString();
private static string SecretKey = ConfigurationManager.AppSettings["SecretKey"].ToString();
public bool BeginFlag = true;
public string local_loginPath = Application.StartupPath "\\LOG\\";
#region 加载窗体时显示单画面
private void Form1_Load(object sender, EventArgs e)
{
createBox();//初始化画面即创建容器根据C的值
this.lbl_appkey.Text = AppKey;//appkey
this.lbl_Secret.Text = SecretKey;//secretkey
//stsTime.Text = DateTime.Now.ToString("yyyy年 MM月 dd日 ") DateTime.Now.ToShortTimeString();
UserControl.CheckForIllegalCrossThreadCalls = false;
if (!Directory.Exists(Application.StartupPath "\\Configs\\"))
{
Directory.CreateDirectory(Application.StartupPath "\\Configs\\");
}
if (!Directory.Exists(local_loginPath))
{
Directory.CreateDirectory(local_loginPath);
}
#region 常规配置
if (!File.Exists(Application.StartupPath "\\Configs\\Config.ini"))
{
File.WriteAllText(Application.StartupPath "\\Configs\\Config.ini", @"D:\d\,60,false", Encoding.Default);
}
string AlltextConfig = File.ReadAllText(Application.StartupPath "\\Configs\\Config.ini", Encoding.Default);
string[] configArray = AlltextConfig.Split(',');
String SaveDir = configArray[0];
int TimeMinute = 0;
try
{
TimeMinute = Convert.ToInt32(configArray[1]);
}
catch
{
TimeMinute = 60;
}
this.timer1.Interval = TimeMinute * 60 * 1000;
this.timer1.Start();
try
{
this.txt_ImageSaveDir.Text = configArray[0];
}
catch
{
}
try
{
this.txt_minute.Text = configArray[1];
}
catch
{
}
try
{
if (configArray[2].Trim() == "true")
{
ck_ClearMoreFile.Checked = true;
}
else
{
ck_ClearMoreFile.Checked = false;
}
}
catch
{
}
#endregion
#region ftp配置
try
{
if (!File.Exists(Application.StartupPath "\\Configs\\Config.ini"))
{
File.WriteAllText(Application.StartupPath "\\Configs\\Config_FTP.ini", "127.0.0.1,21,ruanjian,ruanjian,true,false", Encoding.Default);
}
string innerFtpData = File.ReadAllText(Application.StartupPath "\\Configs\\Config_FTP.ini", Encoding.Default);
string[] arrayFtp = innerFtpData.Split(',');
txtFTPIP.Text = arrayFtp[0];
txtFTPPort.Text = arrayFtp[1];
txtFTPUserName.Text = arrayFtp[2];
txtFTPUserPass.Text = arrayFtp[3];
if (arrayFtp[4] == "true")
{
cl_FTPClearFile.Checked = true;
}
else
{
cl_FTPClearFile.Checked = false;
}
if (arrayFtp[5] == "true")
{
rdbFTPStart.Checked = true;
}
else
{
rdbFTPStop.Checked = true;
}
}
catch
{
}
#endregion
if (rdbFTPStart.Checked)
{
this.Timer_FTP.Start();
}
//解析站点配置
if (!File.Exists(Application.StartupPath "\\Configs\\Config_StationList.ini"))
{
string InnserConfig = "//双斜线注释不再存储该站图片\r\nXXX-XXX\r\nnXXX-nXXX\r\nnXXX-nXXX\r\nXXX(nXXX)";
File.WriteAllText(Application.StartupPath "\\Configs\\Config_StationList.ini", InnserConfig, Encoding.Default);
}
string InnerStationList = txt_StationList.Text;
string[] FilesLine = File.ReadAllLines(Application.StartupPath "\\Configs\\Config_StationList.ini", Encoding.Default);
StringBuilder sbtext = new StringBuilder();
foreach (var item in FilesLine)
{
if (!item.Contains("//"))
{
if (item.Contains("-"))
{
string[] le = item.Split('-');
if (Dic_Local.ContainsKey(le[1].Trim()))
{
Dic_Local[le[1].Trim()] = le[0].Trim();
}
else
{
Dic_Local.Add(le[1].Trim(), le[0].Trim());
}
}
}
sbtext.Append(item.Trim() "\r\n");
}
this.txt_StationList.Text = sbtext.ToString();
}
#endregion
Dictionary<string, string> Dic_Local = new Dictionary<string, string>();
#region 单画面显示按钮
private void btnFrm1_Click(object sender, EventArgs e)
{
c = 1;
btnStop_Click(sender, e);
}
#endregion
#region 四画面显示按钮
private void btnFrm4_Click(object sender, EventArgs e)
{
c = 4;
btnStop_Click(sender, e);
}
#endregion
#region 九画面显示按钮
private void btnFrm9_Click(object sender, EventArgs e)
{
c = 9;
btnStop_Click(sender, e);
}
#endregion
#region 创建播放容器并添加双击事件
private void createBox()
{
this.flowLayoutPanel1.Controls.Clear();//清楚所有容器
if (c == 1)//单画面只需创建一个容器即可
{
PictureBox pic = new PictureBox();
pic.Size = new Size(955, 668);//指定播放容器大小
pic.BackColor = Color.Black;
pic.Name = "picBox0";
this.flowLayoutPanel1.Controls.Add(pic);//创建播放容器
picbox[0] = pic;
handle[0] = picbox[0].Handle;
picbox[0].MouseDoubleClick = new MouseEventHandler(picbox_MouseDoubleClick);//添加鼠标双击击事件,用于全屏播放
}
else//多画面时根据C的值创建容器
{
for (int i = 0; i < c; i )
{
PictureBox pic = new PictureBox();
if (c == 4)
{
pic.Size = new Size(470, 330);//指定播放容器大小4画面
}
else
{
pic.Size = new Size(312, 218);//指定播放容器大小9画面
}
pic.BackColor = Color.Black;
pic.Name = "picBox" i.ToString();
this.flowLayoutPanel1.Controls.Add(pic);//创建播放容器
picbox[i] = pic;
handle[i] = picbox[i].Handle;
pic.Margin = new System.Windows.Forms.Padding(1);
picbox[i].MouseDoubleClick = new MouseEventHandler(picbox_MouseDoubleClick);
}
}
}
#endregion
#region 双击跳转到全屏显示窗口
private void picbox_MouseDoubleClick(object sender, EventArgs e)
{
if (cameraid2 == "")
{
PictureBox picb1 = sender as PictureBox;//取出点击的控件sender
int n = 0;
if (picb1 != null)//点击则非空,否则为空
{
n = Int32.Parse(picb1.Name.Substring(picb1.Name.Length - 1, 1)); //取名字中最后一个字,它正好是控件的index
}
cameraid2 = cameraid1[n];
if (c == 1)
{
bool close = HkAction.Stop(SessionId[0]);//关闭当前所有正在播放的该摄像头
}
else
{
stopall();
}
FullScreenWindow frm = new FullScreenWindow(cameraid2, SessionId[n]);
//定义一个委托,在frm关闭时执行委托函数内容
frm.FormClosed = delegate(object s, FormClosedEventArgs fe)
{
if (c == 1) { HkAction.Play(handle[0], cameraid1[0], SessionId[0]); cameraid2 = ""; }
else
{
startall(); cameraid2 = "";
}
};
frm.Show();
}
else
{
MessageBox.Show("此视频已在全屏播放中,请不要重复点击!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
#endregion
#region 鼠标停在摄像头缩略图上显示播放图标
private void picbox_MouseHover(object sender, EventArgs e)
{
PictureBox picb1 = sender as PictureBox;//取出点击的控件sender
if (picb1 != null)//点击则非空,否则为空
{
picb1.Image = Image.FromFile("2.png");
picb1.SizeMode = PictureBoxSizeMode.CenterImage;
}
}
#endregion
#region 鼠标离开时清除播放图片,重新显示缩略图
private void picbox_MouseLeave(object sender, EventArgs e)
{
PictureBox picb1 = sender as PictureBox;//取出点击的控件sender
if (picb1 != null)//点击则非空,否则为空
{
picb1.Image = null;
}
}
#endregion
#region 鼠标滚动方法
private void Form_MouseWheel(object sender, MouseEventArgs e)
{
//获取光标位置
Point mousePoint = new Point(e.X, e.Y);
//换算成相对本窗体的位置
mousePoint.Offset(this.Location.X, this.Location.Y);
//判断是否在flowLayoutPanel2内
if (flowLayoutPanel2.RectangleToScreen(
flowLayoutPanel2.DisplayRectangle).Contains(mousePoint))
{
//滚动
flowLayoutPanel2.AutoScrollPosition = new Point(0, flowLayoutPanel2.VerticalScroll.Value - e.Delta);
}
}
#endregion
#region 鼠标滚动事件
private void flowLayoutPanel2_MouseHover(object sender, EventArgs e)
{
this.MouseWheel = new MouseEventHandler(Form_MouseWheel);
}
#endregion
#region 停止所有当前播放
private void stopall()
{
for (int s = 0; s < j; s )
{
try
{
HkAction.Stop(SessionId[s]);
}
catch (Exception ex)
{
//MessageBox.Show("异常" ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
a = 0;
}
#endregion
#region 开始所有当前播放
private void startall()
{
try
{
for (int s = 0; s < j; s )
{
HkAction.Play(handle[s], cameraid1[s], SessionId[s]);
}
}
catch (Exception ex)
{
//MessageBox.Show("异常" ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
a = 1;
}
#endregion
#region 刷新按钮
private void btnRefresh_Click(object sender, EventArgs e)
{
stopall();
createBox();
startall();
}
#endregion
/// <summary>
/// 测试流程
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_liucheng_Click(object sender, EventArgs e)
{
if (ThreadGetImage != null)
{
ThreadGetImage.Abort();
ThreadGetImage = null;
}
ThreadGetImage = new Thread(GetImageFun);
ThreadGetImage.Start();
}
Thread ThreadGetImage = null;
public void GetImageFun()
{
try
{
//登录
if (HkAction.GetAccessToken() != null)
{
Console.WriteLine("登录成功");
//this.Text = "登陆成功!";
//获取摄像头列表
string getList = HkAction.playList();
jsonstr = getList;
jsonHandleMy(jsonstr);
}
}
catch (Exception ex)//出现异常则提示
{
//MessageBox.Show("异常!" ex.ToString(), "提示", MessageBoxButtons.OK);
}
//测试不用显示截图
}
int totalNum = 0;
//处理json方法,获取设备列表以缩略图显示并显示摄像头一些信息
public void jsonHandleMy(string str)
{
try
{
string jsonStr = str;
JObject jsonObj = JObject.Parse(jsonStr);
JArray jar = JArray.Parse(jsonObj["cameraList"].ToString());
int a = Int32.Parse(jsonObj["count"].ToString());
totalNum = a;
StringBuilder ShexiangTouListSb = new StringBuilder();
ShexiangTouListSb.Append("更新时间:" System.DateTime.Now.ToString() "\r\n");
for (int cc = 0; cc < totalNum; cc )
{
JObject j = JObject.Parse(jar[cc].ToString());//取第几个摄像头信息放入对象j
string LblName = j["cameraName"].ToString();//取出摄像头名字
//if (LblName.Contains("("))
//{
// LblName = LblName.Split('(')[1].Replace(")", "").Trim();
//}
string isEncrypt = j["isEncrypt"].ToString();//取出摄像头状态
string JiamiState = "未加密";
if (isEncrypt == "0")
{
JiamiState = "未加密";//把摄像头加密状态给label
}
else if (isEncrypt == "1")
{
JiamiState = "已加密";//把摄像头加密状态给label
}
string status = j["status"].ToString();
string deviceSerialA = j["deviceSerial"].ToString();//取出摄像头驱动编号
string zaixianzhuangtai = "离线";
if (!Dic_Local.ContainsKey(deviceSerialA.ToString().Trim()))
{
zaixianzhuangtai = "未获取";//把摄像头状态给label
if (status != "0")
{
zaixianzhuangtai = "在线(未配置获取)";
}
else
{
zaixianzhuangtai = "离线(未配置获取)";
}
}
else
{
if (status == "0")
{
zaixianzhuangtai = "离线";//把摄像头状态给label
}
else
{
zaixianzhuangtai = "在线";//把摄像头状态给label
}
}
ShexiangTouListSb.Append(LblName "-" zaixianzhuangtai "-" JiamiState "\r\n");
}
this.txt_allstate.Text = ShexiangTouListSb.ToString();
for (int m = 0; m < totalNum; m )
{
JObject j = JObject.Parse(jar[m].ToString());//取第几个摄像头信息放入对象j
string status = j["status"].ToString();
string LblName = j["cameraName"].ToString();//取出摄像头名字
if (LblName.Contains("("))//中文名
{
LblName = LblName.Split('(')[0].Replace("(", "").Trim();//括号内部分
}
string deviceSerial = j["deviceSerial"].ToString();//取出摄像头驱动编号
if (status != "0" && Dic_Local.ContainsKey(deviceSerial.Trim()))//在线的时候截缩略图 并且 驱动编号存在于存储列表内
{
DateTime dtNow = System.DateTime.Now;//.ToString("yyyy-MM-dd");
string SaveFileName = System.DateTime.Now.ToString("yyyy_MM_dd_HH_mm") ".jpg";
string Path = txt_ImageSaveDir.Text.Trim() "\\"; // Application.StartupPath "\\ImageSave\\";
if (!System.IO.Directory.Exists(Path))
{
System.IO.Directory.CreateDirectory(Path);
}
if (!Directory.Exists(Path deviceSerial "\\"))
{
Directory.CreateDirectory(Path deviceSerial "\\");
}
string DIrDirInner = dtNow.ToString("yyyy-MM-dd");
if (!Directory.Exists(Path deviceSerial "\\" DIrDirInner "\\"))//存储目录 摄像头编号 日期 文件夹形式
{
Directory.CreateDirectory(Path deviceSerial "\\" DIrDirInner "\\");
}
string CurrentCameraID = j["cameraId"].ToString();
//获取会话开始播放
IntPtr CurrentSessionId = HkAction.AllocSession();//每次点击存放session
if (CurrentSessionId != null)//每次播放申请会话
{
bool play;
try
{
play = HkAction.Play(this.pictureBox1.Handle, CurrentCameraID, CurrentSessionId);
if (play == true)
{
try
{
#region 只存储最新数据 剩下的都删除
try
{
if (this.ck_ClearMoreFile.Checked)//目录下不存储任何历史文件 只存储最新的一条文件
{
//string FileDirsCurrentLocalOp = Path deviceSerial "\\" DIrDirInner "\\";
DirectoryInfo root = new DirectoryInfo(Path deviceSerial "\\");
DirectoryInfo[] Dirs = root.GetDirectories();//日期文件夹目录
foreach (DirectoryInfo item in Dirs)//循环时间目录
{
foreach (FileInfo f in item.GetFiles())//循环删除时间目录下的图形文件
{
string name = f.Name;
string fullName = f.FullName;
File.Delete(fullName);
}//end foreach
}
}//end if (this.ck_ClearMoreFile.Checked)
}
catch
{
}
#endregion
System.Threading.Thread.Sleep(5000);//线程5s截图
//"\\" DIrDirInner "\\"
string CurrentLastSavePath = Path deviceSerial "\\" DIrDirInner "\\" SaveFileName;//带日期目录
if (HkAction.CapturePictureMy(CurrentSessionId, CurrentLastSavePath))//调用SDK截图方法
{
txt_log.Text = System.DateTime.Now ":" LblName "(" deviceSerial ")" "存储成功!\r\n";
}
System.Threading.Thread.Sleep(5000);//下一组截图准备
}
catch (Exception ex)
{
txt_log.Text = System.DateTime.Now ":" LblName "(" deviceSerial ")" ex.Message "\r\n";
}
///停止播放
HkAction.Stop(CurrentSessionId);
HkSDK.OpenSDK_FreeSession(CurrentSessionId.ToString());
//MessageBox.Show(CurrentSessionId " 清空 " LblName);
}
}
catch (Exception ex)
{
txt_log.Text = System.DateTime.Now ":" LblName "(" deviceSerial ")" "异常" ex.Message "\r\n";
}
}
else
{
//MessageBox.Show("申请会话异常!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
txt_log.Text = System.DateTime.Now ":" LblName "(" deviceSerial ")" "申请会话异常" "\r\n";
}
}
else//不在线
{
string txtLeng = "设备离线";
if (!Dic_Local.ContainsKey(deviceSerial.Trim()))
{
txtLeng = "未配置获取";
}
else
{
txtLeng = "设备离线";
}
//存储日志
txt_log.Text = System.DateTime.Now ":" LblName "(" deviceSerial ")" txtLeng "\r\n";
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
//foreach (Control c in flowLayoutPanel2.Controls)
// c.Margin = new Padding(5);
}
/// <summary>
/// 选择存储路径
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_search_Click(object sender, EventArgs e)
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
dialog.Description = "请选择图像文件存储路径(路径中不要包含中文字符!!!)";
DialogResult result = dialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.Cancel)
{
return;
}
string folderPath = dialog.SelectedPath.Trim();
this.txt_ImageSaveDir.Text = folderPath;
DirectoryInfo theFolder = new DirectoryInfo(folderPath);
if (theFolder.Exists)
{
//操作
return;
}
}
/// <summary>
/// 保存配置文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_SaveDir_Click(object sender, EventArgs e)
{
try
{
if (!Directory.Exists(Application.StartupPath "\\Configs\\"))
{
Directory.CreateDirectory(Application.StartupPath "\\Configs\\");
}
#region 常规配置
try
{
//图片存储路径
if (!Directory.Exists(this.txt_ImageSaveDir.Text.Trim()))
{
Directory.CreateDirectory(this.txt_ImageSaveDir.Text.Trim());
}
//上传间隔
int minute = 60;
try
{
minute = Convert.ToInt32(txt_minute.Text.Trim());
}
catch
{
minute = 60;
}
string clearMoreFile = ck_ClearMoreFile.Checked ? "true" : "false";
string InnerConfigContent = this.txt_ImageSaveDir.Text.Trim() "," minute.ToString().Trim() "," clearMoreFile;//目录,下载间隔,是否清除历史文件 true-清除 false-不清除
File.WriteAllText(Application.StartupPath "\\Configs\\Config.ini", InnerConfigContent, Encoding.Default);
}
catch (Exception ex)
{
}
#endregion
#region FTP配置
try
{
string IP = txtFTPIP.Text;
string Port = txtFTPPort.Text;
string UserName = txtFTPUserName.Text;
string UserPass = txtFTPUserPass.Text;
string FtpClear_check = cl_FTPClearFile.Checked ? "true" : "false";
string rdbFTPStarta = rdbFTPStart.Checked ? "true" : "false";
string FtpConfigStr = IP "," Port "," UserName "," UserPass "," FtpClear_check "," rdbFTPStarta;
File.WriteAllText(Application.StartupPath "\\Configs\\Config_FTP.ini", FtpConfigStr, Encoding.Default);
}
catch
{
}
#endregion
#region
try
{
string InnerStationList = txt_StationList.Text;
File.WriteAllText(Application.StartupPath "\\Configs\\Config_StationList.ini", InnerStationList, Encoding.Default);
}
catch
{
}
#endregion
MessageBox.Show("保存配置成功!重启软件以使配置生效!");
}
catch
{
MessageBox.Show("保存配置失败!");
}
}
/// <summary>
/// 时间运行控件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void timer1_Tick(object sender, EventArgs e)
{
if (ThreadGetImage != null)
{
ThreadGetImage.Abort();
ThreadGetImage = null;
}
ThreadGetImage = new Thread(GetImageFun);
ThreadGetImage.Start();
}
//关闭窗口得时候实现
private void PlayMainWindow_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
stopall();//停止播放
HkAction.Close();//反初始化库
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
if (ThreadGetImage != null)
{
ThreadGetImage.Abort();
ThreadGetImage = null;
}
}
//ftp上传组件
private void Timer_FTP_Tick(object sender, EventArgs e)
{
try
{
if (System.DateTime.Now.Hour == 12 && System.DateTime.Now.Minute == 0)
{
string CurrentText = this.txt_log.Text;
this.txt_log.Text = "";
string dir = local_loginPath "Alltimes\\";
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
File.AppendAllText(dir System.DateTime.Now.ToString("yyyyMMdd") ".txt", CurrentText, Encoding.Default);
}
if (Thread_FtpUp != null)
{
Thread_FtpUp.Abort();
Thread_FtpUp = null;
}
Thread_FtpUp = new Thread(FtpUp);
Thread_FtpUp.Start();
}
catch
{
}
}
public Thread Thread_FtpUp = null;
/// <summary>
/// FTP
/// </summary>
EnterpriseDT.Net.Ftp.FTPClient FTP = new EnterpriseDT.Net.Ftp.FTPClient();
/// <summary>
/// FTP上传
/// </summary>
private void FtpUp()
{
try
{
FTP = new FTPClient(this.txtFTPIP.Text.Trim(), int.Parse(this.txtFTPPort.Text.Trim()));
string FilePath = txt_ImageSaveDir.Text "\\";//Application.StartupPath "\\Data\\FtpSend\\";//FTPDown.Properties.Settings.Default.LogPath "\\" Dtime.ToString("yyyyMMddHH") ".xml";
DirectoryInfo Dir = new DirectoryInfo(FilePath);
if (Dir.Exists)
{
FTP.Login(this.txtFTPUserName.Text.Trim(), this.txtFTPUserPass.Text.Trim());
string[] AllDFTPDirs = Directory.GetDirectories(txt_ImageSaveDir.Text "\\");
foreach (var item in AllDFTPDirs)//D:\as\C80672986 精确到编号
{
string CurrentPath = item;
string LastPath = item.Substring(item.LastIndexOf(@"\") 1);
string[] AllInnerDatetimeDir = Directory.GetDirectories(item);//各个日期列表
//循环日期文件夹
try
{
for (int cc = 0; cc < AllInnerDatetimeDir.Length; cc )//循环日期文件夹
{
string CurrentDatETimeFiles = AllInnerDatetimeDir[cc];
string[] StrFiles;
StrFiles = Directory.GetFiles(CurrentDatETimeFiles);
string lastinnerpath = CurrentDatETimeFiles.Substring(CurrentDatETimeFiles.LastIndexOf(@"\") 1);
for (int i = 0; i < StrFiles.Length; i )
{
string FileName = StrFiles[i];
if (File.Exists(FileName))
{
string FileNamePath = local_loginPath "" LastPath ".txt";
#region 上传过得不在上传
try
{
if (!File.Exists(FileName)) File.Create(FileNamePath).Close();
string InnerLogText = File.ReadAllText(FileNamePath, Encoding.Default);
if (InnerLogText.Contains(FileName)) continue;
}
catch
{
}
#endregion
try
{
FTP.ConnectMode = FTPConnectMode.PASV;
FTP.TransferType = FTPTransferType.BINARY;
//bool contains = File.Exists("/" LastPath);
//循环上传文件夹
try
{
Console.WriteLine(lastinnerpath);
//FTP.ChDir("/" LastPath);
String[] files = FTP.Dir("/", false);
bool flag = false;
foreach (var iteminner in files)//循环编号文件夹
{
if (iteminner.Contains(LastPath))//是否包含编号目录
{
flag = true;
}//end if(iteminner.Contains(LastPath))
}// foreach (var iteminner in files)
if (!flag)
{
FTP.MkDir("/" LastPath);
}
//是否存在内部的日期文件夹
bool innerFilesFlag = false;
foreach (var iteminner in files)//循环编号文件夹
{
string[] filesInner = FTP.Dir("/" LastPath, false);
foreach (var itemInner in filesInner)
{
if (iteminner.Contains(lastinnerpath))
{
innerFilesFlag = true;
}
}//end foreach (var itemInner in filesInner)内层循环
}//end foreach (var iteminner in files)//循环编号文件夹
if (!innerFilesFlag)//不存在内部的日期文件夹
{
FTP.MkDir("/" LastPath "/" lastinnerpath);
} //创建内部文件夹日期文件夹
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
//FTP.MkDir("/" LastPath);
}
string dirLujing = "\\" LastPath "\\" lastinnerpath "\\" Path.GetFileName(StrFiles[i]);
FTP.Put(FileName, dirLujing);//上传目录按照目录上传文件
#region 存储上传文件名
try
{
File.AppendAllText(FileNamePath, FileName "\r\n", Encoding.Default);
}
catch
{
}
#endregion
Console.WriteLine(FileName);
if (cl_FTPClearFile.Checked)//如果FTP上传后删除文件选中 则清除FTP文件
{
File.Delete(FileName);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
FTP.QuitImmediately();
}
}//if (File.Exists(FileName))
} //for (int i = 0; i < str.Length; i )
}// //循环日期文件夹for (int cc = 0; cc < AllInnerDatetimeDir.Length; cc )
}
catch
{
FTP.QuitImmediately();
}
}//end foreach
FTP.QuitImmediately();
}//end if
}
catch { }
}
private void button1_Click(object sender, EventArgs e)
{
//if (System.DateTime.Now.Hour == 12 && System.DateTime.Now.Minute == 0)
{
string CurrentText = this.txt_log.Text;
this.txt_log.Text = "";
string dir = local_loginPath "Alltimes\\";
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
File.AppendAllText(dir System.DateTime.Now.ToString("yyyyMMdd") ".txt", CurrentText, Encoding.Default);
}
try
{
if (Thread_FtpUp != null)
{
Thread_FtpUp.Abort();
Thread_FtpUp = null;
}
Thread_FtpUp = new Thread(FtpUp);
Thread_FtpUp.Start();
}
catch
{
}
}
//通讯会话
string Local_sessionid = "";
//摄像头ID
string Local_Cameraid = "";
//摄像头通道号
int Local_cameraNO = 1;
ys000.HkSDK.PTZCommand enCommand = HkSDK.PTZCommand.AUTO;
ys000.HkSDK.PTZAction Action = HkSDK.PTZAction.STOP;
/// <summary>
/// 向上按下显示
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_up_MouseDown(object sender, MouseEventArgs e)
{
try
{
if (string.IsNullOrEmpty(Local_sessionid))
{
return;
}
int result = ys000.HkSDK.OpenSDK_PTZCtrlEx(Local_Cameraid, Local_Cameraid, Local_cameraNO, HkSDK.PTZCommand.UP, HkSDK.PTZAction.START, 2);
if (result == 1)
{
Console.WriteLine("OK");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
}
//向上放开执行
private void btn_up_MouseUp(object sender, MouseEventArgs e)
{
try
{
int result = ys000.HkSDK.OpenSDK_PTZCtrlEx(Local_Cameraid, Local_Cameraid, Local_cameraNO, HkSDK.PTZCommand.UP, HkSDK.PTZAction.STOP, 2);
if (result == 1)
{
Console.WriteLine("OK");
}
}
catch
{
}
}
}
}
好例子网口号:伸出你的我的手 — 分享!
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明


网友评论
我要评论