using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.NetworkInformation;
namespace HexcalMC.Base
{
//==========================================================================================
//通用功能类
public class RichTextUnit
{
public static float MSize = 16;
public static void SetFont(RichTextBox mRichTextBox, Color mColor, bool bBold = false, float size = 16)
{
mRichTextBox.SelectionColor = mColor;
if (bBold)
mRichTextBox.SelectionFont = new System.Drawing.Font("微软雅黑", size, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel, ((byte)(134)));
else
mRichTextBox.SelectionFont = new System.Drawing.Font("微软雅黑", size, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(134)));
}
public static void SetText(RichTextBox mRichTextBox, string strText, Color mColor, bool bBold = false, float size = 16)
{
mRichTextBox.Invoke(((EventHandler)delegate
{
RichTextUnit.SetFont(mRichTextBox, mColor, bBold, size);
mRichTextBox.SelectedText = strText;
}));
}
public static void SetXmlText(RichTextBox mRichTextBox, string strText, float size = 16)
{
mRichTextBox.Invoke(((EventHandler)delegate
{
int iFirstInx = strText.IndexOf("");
int iSecondInx = strText.IndexOf("?>");
#region PARSE THROUGH TEXT DATA
for (int i = 0; i < strText.Length; i++)
{
if (i >= iFirstInx && i <= iSecondInx + 1)
{
RichTextUnit.SetFont(mRichTextBox, Color.Blue, false, size);
mRichTextBox.SelectedText = strText[i].ToString();
}
else
{
switch (strText[i])
{
case '<':
{
RichTextUnit.SetFont(mRichTextBox, Color.Blue, false, size);
mRichTextBox.SelectedText = strText[i].ToString();
if (strText[i + 1] == '/')
{
mRichTextBox.SelectedText = strText[i + 1].ToString();
i++;
}
RichTextUnit.SetFont(mRichTextBox, Color.DarkRed, false, size);
}
break;
case '>':
{
RichTextUnit.SetFont(mRichTextBox, Color.Blue, false, size);
mRichTextBox.SelectedText = strText[i].ToString();
RichTextUnit.SetFont(mRichTextBox, Color.Black, false, size);
}
break;
case '/':
{
RichTextUnit.SetFont(mRichTextBox, Color.Blue, false, size);
mRichTextBox.SelectedText = strText[i].ToString();
}
break;
case '=':
{
if (strText[i + 1] == '"')
{
RichTextUnit.SetFont(mRichTextBox, Color.Black, true, size);
mRichTextBox.SelectedText = "=" + '"'.ToString();
i++;
}
}
break;
case '"':
{
RichTextUnit.SetFont(mRichTextBox, Color.Blue, false, size);
mRichTextBox.SelectedText = strText[i].ToString();
if (strText[i - 1] == '=')
RichTextUnit.SetFont(mRichTextBox, Color.Black, true, size);
else
RichTextUnit.SetFont(mRichTextBox, Color.DarkRed, false, size);
}
break;
case '!':
{
RichTextUnit.SetFont(mRichTextBox, Color.Green, false, size);
mRichTextBox.SelectedText = strText[i].ToString();
}
break;
case '\r':
{
if (strText[i + 1] == '\n')
{
mRichTextBox.SelectedText = "\r\n";
i++;
}
}
break;
default:
mRichTextBox.SelectedText = strText[i].ToString();
break;
}
}
}
#endregion
mRichTextBox.SelectedText = Environment.NewLine;
}));
}
public static void SetCncText(RichTextBox mRichTextBox, string strText, float size = 16)
{
mRichTextBox.Invoke(((EventHandler)delegate
{
#region PARSE THROUGH TEXT DATA
for (int i = 0; i < strText.Length; i++)
{
switch (strText[i])
{
case '%':
RichTextUnit.SetFont(mRichTextBox, Color.Red, false, size);
mRichTextBox.SelectedText = strText[i].ToString();
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
RichTextUnit.SetFont(mRichTextBox, Color.DeepSkyBlue, false, size);
mRichTextBox.SelectedText = strText[i].ToString();
break;
default:
RichTextUnit.SetFont(mRichTextBox, Color.White, false, size);
mRichTextBox.SelectedText = strText[i].ToString();
break;
}
}
#endregion
}));
}
}
public class MyBase
{
#region 内存回收
[DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
///
/// 释放内存
///
public static void ClearMemory()
{
GC.Collect();
GC.WaitForPendingFinalizers();
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
}
}
public static void ClearMemory_PCDMIS()
{
Process[] mProcess = Process.GetProcessesByName("PCDLRN");
for (int i = 0; i < mProcess.Length; i++)
{
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
SetProcessWorkingSetSize(mProcess[i].Handle, -1, -1);
}
}
}
#endregion
public static void KillSoftware(string strSoftwareName)
{
Process[] xc = Process.GetProcesses();
try
{
foreach (Process xc1 in xc)
{
if (xc1.ProcessName.ToLower() == strSoftwareName.ToLower())
{
xc1.Kill();
}
}
}
catch (Exception ex)
{
MyBase.TraceWriteLine("Kill " + strSoftwareName + " Failed: " + ex.ToString());
}
}
#region 界面控件操作
///
/// 根据指定容器和控件名字,获得控件
///
/// 容器
/// 控件名字
/// 控件
public static object GetControlInstance(object obj, string strControlName, System.Windows.Forms.Form mainForm)
{
IEnumerator controls = null; //所有控件
Control c = null; //当前控件
Object cResult = null; //查找结果
if (obj.GetType() == mainForm.GetType()) //窗体
{
controls = mainForm.Controls.GetEnumerator();
}
else //控件
{
controls = ((Control)obj).Controls.GetEnumerator();
}
while (controls.MoveNext()) //遍历操作
{
c = (Control)controls.Current; //当前控件
if (c.HasChildren) //当前控件是个容器
{
cResult = GetControlInstance(c, strControlName, mainForm); //递归查找
if (cResult == null) //当前容器中没有,跳出,继续查找
continue;
else //找到控件,返回
return cResult;
}
else if (c.Name == strControlName) //不是容器,同时找到控件,返回
{
return c;
}
}
return null; //控件不存在
}
public static object GetChildControl(object obj, string strControlName)
{
Control mCtrl = null; //当前控件
IEnumerator controls = ((Control)obj).Controls.GetEnumerator();
while (controls.MoveNext())
{
mCtrl = (Control)controls.Current; //当前控件
if (mCtrl.Name == strControlName)
{
return mCtrl;
}
}
return null; //控件不存在
}
public static void AddDebugText(TextBox tb, string str, int length = 200)
{
try
{
TraceWriteLine(str);
string strTime = DateTime.Now.ToString("HH:mm:ss") + "--";
tb.Text += (strTime + str);
tb.Text += "\r\n";
tb.Select(tb.TextLength, 0);
tb.ScrollToCaret();
if (tb.Lines.Length > length)
{
tb.Clear();
}
}
finally
{
}
}
///
/// 向RichTextBox控件中添加文本信息
///
/// RichTextBox控件类
/// 要显示的文本信息内容
/// 文本显示的颜色
public static void AddDebugTextToRtb(RichTextBox rtb, string str, Color mColor = new Color())
{
try
{
TraceWriteLine(str); //将文本信息同步到debug.txt文件中
rtb.BeginInvoke((EventHandler)delegate
{
Color setColor = Color.Black;
if (mColor == new Color())
{
if (str.ToUpper().Contains("ERROR") || str.ToUpper().Contains("错误") ||
str.ToUpper().Contains("出错") || str.ToUpper().Contains("EXCEPTION") ||
str.ToUpper().Contains("异常") || str.ToUpper().Contains("失败"))
{
setColor = Color.Red;
}
else if (str.ToUpper().Contains("WARNING") || str.ToUpper().Contains("警告"))
{
setColor = Color.DarkOrange;
}
}
else
{
setColor = mColor;
}
string strText = str + Environment.NewLine; //DateTime.Now.ToString("HH:mm:ss.fff") + "--" +
rtb.SelectionStart = rtb.TextLength;
if (string.IsNullOrEmpty(str))
RichTextUnit.SetText(rtb, " " + Environment.NewLine, setColor, false, 14);
else
RichTextUnit.SetText(rtb, strText, setColor, false, 14);
if (rtb.Lines.Length > 2000)
{
rtb.Select(0, rtb.TextLength / 2);
rtb.Cut();
}
rtb.ScrollToCaret();
});
}
catch
{
}
}
///
/// 写debug文件,记录程序过程
///
/// 要写入日志的内容
public static void TraceWriteLine(string str)
{
try
{
Trace.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "--" + str);
Trace.Unindent();
Trace.Flush();
}
catch
{
}
}
public static string InputBox(string caption, string hint, string defaultTxt, string btn1 = "OK",
string btn2 = "Cancel", char strstyle = '*', bool bShowData = false)
{
if (strstyle == '\0')
strstyle = '*';
System.Windows.Forms.Form inputForm = new System.Windows.Forms.Form();
inputForm.MinimizeBox = false;
inputForm.MaximizeBox = false;
inputForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
inputForm.StartPosition = FormStartPosition.CenterScreen;
inputForm.Width = 230;
inputForm.Height = 170;
inputForm.Text = caption;
inputForm.Font = new System.Drawing.Font("宋体", 16F, System.Drawing.FontStyle.Regular,
System.Drawing.GraphicsUnit.Pixel, ((byte)(134)));
Label lbl = new Label();
lbl.Text = hint;
lbl.Left = 10;
lbl.Top = 20;
lbl.Parent = inputForm;
lbl.AutoSize = true;
TextBox tb = new TextBox();
tb.Left = 30;
tb.Top = 45;
tb.Width = 165;
tb.Parent = inputForm;
tb.Text = defaultTxt;
if (bShowData == false)
tb.PasswordChar = strstyle;
tb.SelectAll();
Button btnok = new Button();
btnok.Left = 30;
btnok.Top = 80;
btnok.Height = 30;
btnok.Parent = inputForm;
btnok.Text = btn1;
inputForm.AcceptButton = btnok; //回车响应
btnok.DialogResult = DialogResult.OK;
Button btncancal = new Button();
btncancal.Left = 120;
btncancal.Top = 80;
btncancal.Height = 30;
btncancal.Parent = inputForm;
btncancal.Text = btn2;
btncancal.DialogResult = DialogResult.Cancel;
try
{
if (inputForm.ShowDialog() == DialogResult.OK)
{
return tb.Text;
}
else
{
return null;
}
}
finally
{
inputForm.Dispose();
}
}
///
/// 操作提示框,0 = 取消; 1 = 第一个按钮; 2 = 第二个按钮
///
/// 错误信息
/// 标题
/// 第一个按钮名字
/// 第二个按钮名字
/// 第三个按钮名字
/// 背景颜色,默认无色,1=红色
///
public static int MessageBox(string strError, string caption, string btnName1 = "YES", string btnName2 = "NO",
string btnName3 = "Cancel", int iColor = 0)
{
System.Windows.Forms.Form errorForm = new System.Windows.Forms.Form();
errorForm.MinimizeBox = false;
errorForm.MaximizeBox = false;
errorForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
errorForm.StartPosition = FormStartPosition.CenterScreen;
errorForm.Width = 480;
errorForm.Height = 300;
errorForm.Text = caption;
errorForm.Font = new System.Drawing.Font("宋体", 16F, System.Drawing.FontStyle.Regular,
System.Drawing.GraphicsUnit.Pixel, ((byte)(134)));
TextBox tb = new TextBox();
tb.Parent = errorForm;
tb.Text = strError;
tb.Multiline = true;
tb.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
tb.Location = new System.Drawing.Point(20, 20);
tb.Size = new System.Drawing.Size(440, 170);
tb.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
tb.Font = new Font("宋体", 20F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
if (iColor == 1)
tb.BackColor = Color.Red;
Button btnYes = new Button();
btnYes.Location = new System.Drawing.Point(30, 210);
btnYes.Size = new System.Drawing.Size(100, 40);
btnYes.Parent = errorForm;
btnYes.Text = btnName1;
btnYes.DialogResult = DialogResult.Yes;
errorForm.AcceptButton = btnYes; //回车响应
Button btnNo = new Button();
btnNo.Location = new System.Drawing.Point(190, 210);
btnNo.Size = new System.Drawing.Size(100, 40);
btnNo.Parent = errorForm;
btnNo.Text = btnName2;
btnNo.DialogResult = DialogResult.No;
errorForm.AcceptButton = btnNo; //回车响应
Button btncancal = new Button();
btncancal.Location = new System.Drawing.Point(350, 210);
btncancal.Size = new System.Drawing.Size(100, 40);
btncancal.Parent = errorForm;
btncancal.Text = btnName3;
btncancal.DialogResult = DialogResult.Cancel;
errorForm.AcceptButton = btncancal; //回车响应
try
{
btnYes.Select();
switch (errorForm.ShowDialog())
{
case DialogResult.Yes: return 1;
case DialogResult.No: return 2;
default: return 0;
}
}
finally
{
errorForm.Dispose();
}
}
[DllImport("User32.dll")]
private static extern bool SetCursorPos(int x, int y);
static public void SetCursorPosXy(int dx, int dy)
{
SetCursorPos(dx, dy);
}
static public void SetCursorPosXy(Point point)
{
System.Windows.Forms.Cursor.Position = point;
}
#endregion
///
/// CopyFiles 函数
///
/// 源路径文件夹路径
/// 目标文件夹路径
/// 文件夹名称
///
public static int CopyFiles(string strSourceFilePath, string strDesFilePath, string strRemak)
{
try
{
if (!Directory.Exists(strDesFilePath))
{
Directory.CreateDirectory(strDesFilePath);
}
DirectoryInfo sDir = new DirectoryInfo(strSourceFilePath);
FileInfo[] fileArray = sDir.GetFiles();
foreach (FileInfo file in fileArray)
{
file.CopyTo(strDesFilePath + "\\" + file.Name, true);
}
System.Windows.Forms.MessageBox.Show("传输" + strRemak + "文件夹中的所有文件成功! ", "提示", MessageBoxButtons.OK,
MessageBoxIcon.Information);
return 1;
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show("传输" + strRemak + "文件夹中的文件错误!原因: " + ex.ToString(), "提示",
MessageBoxButtons.OK, MessageBoxIcon.Information);
return 0;
}
}
}
public class HardwareInfoBase
{
/// 获取指定驱动器的空间总大小(单位为B) ,只需输入代表驱动器的字母即可
public static long GetHardDiskSpace(string strHardDiskName)
{
long totalSize = new long();
strHardDiskName = strHardDiskName + ":\\";
System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();
foreach (System.IO.DriveInfo drive in drives)
{
if (drive.Name == strHardDiskName)
{
totalSize = drive.TotalSize;
break;
}
}
return totalSize;
}
/// 获取指定驱动器的剩余空间总大小(单位为B) ,只需输入代表驱动器的字母即可
public static long GetHardDiskFreeSpace(string strHardDiskName)
{
long freeSpace = new long();
strHardDiskName = strHardDiskName + ":\\";
System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();
foreach (System.IO.DriveInfo drive in drives)
{
if (drive.Name == strHardDiskName)
{
freeSpace = drive.TotalFreeSpace;
break;
}
}
return freeSpace;
}
/// 获取指定驱动器的剩余空间总大小(单位为K) ,只需输入代表驱动器的字母即可
public static long GetHardDiskFreeSpace_K(string strHardDiskName)
{
return GetHardDiskFreeSpace(strHardDiskName) / 1024;
}
/// 获取指定驱动器的剩余空间总大小(单位为M) ,只需输入代表驱动器的字母即可
public static long GetHardDiskFreeSpace_M(string strHardDiskName)
{
return GetHardDiskFreeSpace_K(strHardDiskName) / 1024;
}
/// 获取指定驱动器的剩余空间总大小(单位为G) ,只需输入代表驱动器的字母即可
public static long GetHardDiskFreeSpace_G(string strHardDiskName)
{
return GetHardDiskFreeSpace_M(strHardDiskName) / 1024;
}
}
//==================================================================================================FileIni
//Ini 文件操作类
public class FileIni
{
[DllImport("kernel32.dll")]
public static extern IntPtr _lopen(string lpPathName, int iReadWrite);
[DllImport("kernel32.dll")]
public static extern bool CloseHandle(IntPtr hObject);
public const int OfReadwrite = 2;
public const int OfShareDenyNone = 0x40;
public static readonly IntPtr HfileError = new IntPtr(-1);
//判断文件是否被占用 占用=true 未占用 = false
public static bool IsFileOccupied(string path)
{
if (!File.Exists(path))
return true;
IntPtr vHandle = _lopen(path, OfReadwrite | OfShareDenyNone);
if (vHandle == HfileError)
return true;
CloseHandle(vHandle);
return false;
}
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal,
int size, string filePath);
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileInt(string section, string key, int def, string filePath);
public static bool IsFileExists(string path)
{
if (!(File.Exists(path)))
{
MessageBox.Show("文件:" + path + "不存在", "ini文件不存在");
return false;
}
return true;
}
//=====================//=====================//=====================Write data
#region 写INI参数
///
/// 对ini文件进行写操作
///
/// ini文件路径
/// 配置节
/// 键名
/// 要写入的string字符串
public static void WriteString(string path, string section, string key, string value)
{
// section=配置节,key=键名,value=键值,path=路径
WritePrivateProfileString(section, key, value, path);
}
public static void WriteInt(string path, string section, string key, int value = 0)
{
string strRead = ReadString(path, section, key);
string[] strArr = strRead.Split(new char[] { ';' });
string strNote = ";";
string strWrite;
if (strArr.Length > 1) //保留原有注释
{
for (int i = 1; i < strArr.Length; i++)
strNote += strArr[i];
strWrite = value.ToString() + strNote;
}
else
{
strWrite = value.ToString();
}
WritePrivateProfileString(section, key, strWrite, path);
}
public static void WriteDouble(string path, string section, string key, double value = 0)
{
string strRead = ReadString(path, section, key);
string[] strArr = strRead.Split(new char[] { ';' });
string strNote = ";";
string strWrite;
if (strArr.Length > 1) //保留原有注释
{
for (int i = 1; i < strArr.Length; i++)
strNote += strArr[i];
strWrite = value.ToString() + strNote;
}
else
{
strWrite = value.ToString();
}
WritePrivateProfileString(section, key, strWrite, path);
}
public static void WriteBool(string path, string section, string key, bool value = false)
{
string strValue = (value ? "1" : "0");
string strRead = ReadString(path, section, key);
string[] strArr = strRead.Split(new char[] { ';' });
string strNote = ";";
string strWrite;
if (strArr.Length > 1) //保留原有注释
{
for (int i = 1; i < strArr.Length; i++)
strNote += strArr[i];
strWrite = strValue + strNote;
}
else
{
strWrite = strValue;
}
WritePrivateProfileString(section, key, strWrite, path);
}
#endregion
//=====================//=====================//=====================Read data
#region 读INI参数
///
/// 从ini配置文件中读取字符串
///
/// ini文件路径
/// 配置节名称
/// 键名
/// 要读取的string类型内容
public static string ReadString(string path, string section, string key)
{
// 每次从ini中读取多少字节 // section=配置节,key=键名,temp=上面,path=路径
System.Text.StringBuilder temp = new System.Text.StringBuilder(255);
GetPrivateProfileString(section, key, "", temp, 255, path);
String str = temp.ToString();
string[] strArr = str.Split(new char[] { ';' });
string strRead = "";
if (strArr.Length > 0)
{
strRead = strArr[0];
}
return strRead;
}
///
/// 从ini配置文件中读取Int类型
///
/// ini文件路径
/// 配置节名称
/// 键名
/// 读不到时默认返回值:0
/// 要读取的Int类型数据
public static int ReadInt(string path, string section, string key, int defValue = 0)
{
return GetPrivateProfileInt(section, key, defValue, path);
}
public static double ReadDouble(string path, string section, string key, double defValue = 0)
{
System.Text.StringBuilder temp = new System.Text.StringBuilder(255);
GetPrivateProfileString(section, key, defValue.ToString(), temp, 255, path);
String str = temp.ToString();
string[] strArr = str.Split(new char[] { ';' });
double reData;
if (strArr.Length > 0)
{
reData = Convert.ToDouble(strArr[0]);
}
else
{
reData = defValue;
}
return reData;
}
public static bool ReadBool(string path, string section, string key, int defValue = 0)
{
int val = GetPrivateProfileInt(section, key, defValue, path);
if (val != 0)
return true;
else
return false;
}
#endregion
}
//==================================================================================================SoundBase
///
/// 声音播放类
///
public class SoundBase
{
//public static WMPLib.WindowsMediaPlayer WMPlayer = new WMPLib.WindowsMediaPlayer();
////方法 1
//public static void OpenWinMediaPlayer(string FileName)
//{
// if (!System.IO.File.Exists(FileName))
// {
// MessageBox.Show("File does not exist!");
// return;
// }
// WMPlayer.URL = FileName;
//}
//public static void OpenWinMediaPlayer(WMPLib.WindowsMediaPlayer WinMediaPlayer, string FileName)
//{
// if (!System.IO.File.Exists(FileName))
// {
// MessageBox.Show("File does not exist!");
// return;
// }
// WinMediaPlayer.URL = FileName;
//}
//public static void OpenWinMediaPlayerDialogFile()
//{
// OpenFileDialog FileDialog = new OpenFileDialog();
// FileDialog.AddExtension = true;
// FileDialog.CheckFileExists = true;
// FileDialog.CheckPathExists = true;
// //the next sentence must be in single line
// FileDialog.Filter = "WAV文件(*.wav)|*.wav|MP3文件(*.mp3)|*.mp3|VCD文件(*.dat)|*.dat|Audio文件(*.avi)|*.avi|所有文件 (*.*)|*.*";
// FileDialog.DefaultExt = "*.mp3";
// if (FileDialog.ShowDialog() == DialogResult.OK)
// {
// WMPlayer.URL = FileDialog.FileName;
// }
//}
//public static void OpenWinMediaPlayerDialogFile(WMPLib.WindowsMediaPlayer WinMediaPlayer)
//{
// OpenFileDialog FileDialog = new OpenFileDialog();
// FileDialog.AddExtension = true;
// FileDialog.CheckFileExists = true;
// FileDialog.CheckPathExists = true;
// //the next sentence must be in single line
// FileDialog.Filter = "WAV文件(*.wav)|*.wav|MP3文件(*.mp3)|*.mp3|VCD文件(*.dat)|*.dat|Audio文件(*.avi)|*.avi|所有文件 (*.*)|*.*";
// FileDialog.DefaultExt = "*.mp3";
// if (FileDialog.ShowDialog() == DialogResult.OK)
// {
// WinMediaPlayer.URL = FileDialog.FileName;
// }
//}
//方法 2
public static void SndPlayerPlay(string fileName)
{
if (!System.IO.File.Exists(fileName))
{
MessageBox.Show("File does not exist!");
return;
}
System.Media.SoundPlayer sndPlayer = new System.Media.SoundPlayer(fileName);
sndPlayer.Load();
sndPlayer.Play();
}
//方法 3
public static void SpVoicePlay(string fileName)
{
//if (!System.IO.File.Exists(FileName))
//{
// MessageBox.Show("File does not exist!");
// return;
//}
//SpeechLib.SpVoiceClass pp = new SpeechLib.SpVoiceClass();
//SpeechLib.SpFileStreamClass spFs = new SpeechLib.SpFileStreamClass();
//spFs.Open(FileName, SpeechLib.SpeechStreamFileMode.SSFMOpenForRead, true);
//SpeechLib.ISpeechBaseStream Istream = spFs as SpeechLib.ISpeechBaseStream;
//pp.SpeakStream(Istream, SpeechLib.SpeechVoiceSpeakFlags.SVSFIsFilename);
//spFs.Close();
}
//方法 4 (蜂鸣器--控制台扬声器)
public static void Beep(int frequency, int duration)
{
//振动的Hz频率; //持续的时间,单位“毫秒”。
Console.Beep(frequency, duration);
}
}
//==================================================================================================
///
/// 数据格式化或校验检测
///
class FormatCheckBase
{
///
/// 检测是否为十六进制字符串,长度不够在前面添加0
///
/// 输入字符串
/// 长度
/// 输出字符串
/// 检测结果
public static void FormatChecking16(string strInput, int length, out string strOutput, out Boolean valid)
{
strOutput = "";
valid = true;
byte temp;
if ((strInput.Length <= length) & (strInput.Length > 0))
{
for (int i = 0; i < strInput.Length; i++)
{
try
{
temp = Convert.ToByte(strInput[i].ToString(), 16);
}
catch
{
valid = false;
strOutput = "";
break;
}
strOutput += strInput[i];
}
if (valid & (strInput.Length < length))
{
for (int j = 0; j < length - strInput.Length; j++)
{
strOutput = "0" + strOutput;
}
}
}
else
{
valid = false;
strOutput = "";
}
}
///
/// 检测是否为十进制字符串,长度不够在前面添加0
///
/// 输入字符串
/// 长度
/// 输出字符串
/// 检测结果
public static bool FormatChecking10(string strInput, int length, out string strOutput)
{
strOutput = "";
byte temp;
try
{
if ((strInput.Length <= length) & (strInput.Length > 0))
{
for (int i = 0; i < strInput.Length; i++)
{
try
{
temp = Convert.ToByte(strInput[i].ToString(), 10);
}
catch
{
strOutput = "";
return false;
}
strOutput += strInput[i];
}
if (strInput.Length < length)
{
for (int j = 0; j < length - strInput.Length; j++)
{
strOutput = "0" + strOutput;
}
}
}
else
{
strOutput = "";
return false;
}
}
catch (Exception ex)
{
MessageBox.Show("格式转换错误:" + ex.Message);
return false;
}
return true;
}
///
/// 每隔n个字符插入一个字符
///
/// 从右边开始插入
/// 源字符串
/// 间隔字符数
/// 待插入值
/// 待补充值,最后不足间隔字符数时,用此字符补齐;Supplement=""时,不补任何字符。
/// 返回新生成字符串
public static string InsertFormat(bool isRight, string input, int interval, string value, string supplement)
{
if (!isRight) //从左边开始插入
{
for (int i = interval; i < input.Length; i += interval + 1)
{
input = input.Insert(i, value);
}
if (supplement != "")
{
do
{
if ((input.Length + 1) % (interval + 1) != 0)
{
input = input + supplement;
}
} while ((input.Length + 1) % (interval + 1) != 0);
}
}
else //从右边开始插入
{
for (int i = input.Length - interval; i > 0; i -= interval)
{
input = input.Insert(i, value);
}
if (supplement != "")
{
do
{
if ((input.Length + 1) % (interval + 1) != 0)
{
input = supplement + input;
}
} while ((input.Length + 1) % (interval + 1) != 0);
}
}
return input;
}
///
/// BCC校验,返回校验后的字符串
///
/// 待校验字符串
/// 返回结果
public static string GetBcc(string strCmd)
{
if (strCmd.Length >= 2)
{
byte[] buffer = Encoding.Default.GetBytes(strCmd);
byte byteBcc = buffer[0];
for (int i = 1; i < buffer.Length; i++)
byteBcc ^= buffer[i];
return Convert.ToChar(byteBcc).ToString();
}
else
{
return null;
}
}
///
/// BCC校验,返回校验后的数组
///
/// 待校验数组
/// 返回结果
public static byte[] GetBcc(byte[] byteData)
{
byte[] byteWrite = new byte[byteData.Length + 1];
if (byteData.Length >= 2)
{
byteData.CopyTo(byteWrite, 0);
byte byteBcc = byteData[0];
for (int i = 1; i < byteData.Length; i++)
byteBcc ^= byteData[i];
byteWrite[byteWrite.Length - 1] = byteBcc;
return byteWrite;
}
else
{
return null;
}
}
///
/// CRC16校验函数
///
public class Crc16Check
{
private const int CrcLen = 0;
// Table of CRC values for high-order byte
#region
static readonly byte[] AuchCrcHi = new byte[]
{
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
};
#endregion
// Table of CRC values for low-order byte
#region
static readonly byte[] AuchCrcLo = new byte[]
{
0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06,
0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD,
0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09,
0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A,
0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4,
0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3,
0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4,
0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A,
0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29,
0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED,
0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60,
0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67,
0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F,
0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68,
0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E,
0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71,
0x70, 0xB0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92,
0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C,
0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B,
0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B,
0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42,
0x43, 0x83, 0x41, 0x81, 0x80, 0x40
};
#endregion
///
/// 计算CRC16校验值 返回一个ushort类型的值,如果要返回Crc高字节和低字节,可重写CalculateCrc16函数为:
///
/// 待校验数组
/// 输出高字节
/// 输出低字节
/// 输出校验值
public static ushort CalculateCrc16(byte[] buffer, out byte crcHi, out byte crcLo)
{
crcHi = 0xff; // high crc byte initialized
crcLo = 0xff; // low crc byte initialized
for (int i = 0; i < buffer.Length - CrcLen; i++)
{
int crcIndex = crcHi ^ buffer[i]; // calculate the crc lookup index
crcHi = (byte)(crcLo ^ AuchCrcHi[crcIndex]);
crcLo = AuchCrcLo[crcIndex];
}
return (ushort)(crcHi << 8 | crcLo);
}
}
}
//==================================================================================================ConvertBase
///
/// 数据转换类
///
class ConvertBase
{
#region 图像 <--> 数组
///
/// 图像转换为Byte数组
///
static public byte[] ImageToByteArray(Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return ms.ToArray();
}
///
/// Byte数组转换为图像
///
static public Image ByteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
#endregion
#region 字符串 -> 字节数组
///
/// 十六进制(hexadecimal)字符串转换为字节数组
///
///
///
public static byte[] HexStringToBytes(string str)
{
str = str.Replace(" ", "");
byte[] buffer = new byte[str.Length / 2];
for (int i = 0; i < str.Length; i += 2)
{
buffer[i / 2] = (byte)Convert.ToByte(str.Substring(i, 2), 16);
}
return buffer;
}
///
/// 十进制(Decimalism)字符串转换为字节数组
///
///
///
public static byte[] DecimalStringToBytes(string str)
{
str = str.Replace(" ", "");
byte[] buffer = new byte[str.Length];
for (int i = 0; i < str.Length; i++)
{
buffer[i] = (byte)Convert.ToByte(str.Substring(i, 1), 10);
}
return buffer;
}
#endregion
#region DataGridView -> DataTable 和 DataSet
public static DataTable GetDataTableFromDataGridView(DataGridView dv)
{
DataTable dt = new DataTable();
DataColumn dc;
for (int i = 0; i < dv.Columns.Count; i++)
{
dc = new DataColumn();
dc.ColumnName = dv.Columns[i].HeaderText.ToString();
dt.Columns.Add(dc);
}
for (int j = 0; j < dv.Rows.Count - 1; j++)
{
DataRow dr = dt.NewRow();
for (int x = 0; x < dv.Columns.Count; x++)
{
dr[x] = dv.Rows[j].Cells[x].Value;
}
dt.Rows.Add(dr);
}
return dt;
}
public static DataSet GetDataSetFromDataGridView(DataGridView ucgrd)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
for (int j = 0; j < ucgrd.Columns.Count; j++)
{
dt.Columns.Add(ucgrd.Columns[j].HeaderCell.Value.ToString());
}
for (int j = 0; j < ucgrd.Rows.Count; j++)
{
DataRow dr = dt.NewRow();
for (int i = 0; i < ucgrd.Columns.Count; i++)
{
if (ucgrd.Rows[j].Cells[i].Value != null)
{
dr[i] = ucgrd.Rows[j].Cells[i].Value.ToString();
}
else
{
dr[i] = "";
}
}
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
return ds;
}
#endregion
#region ListBox.Items, ComboBox.Items -> string[]
public static string[] GetStringsFromListBox(ListBox mListBox)
{
string[] strings = new string[mListBox.Items.Count];
for (int i = 0; i < mListBox.Items.Count; i++)
{
strings[i] = mListBox.Items[i].ToString();
}
return strings;
}
public static string[] GetStringsFromListBox(ComboBox mComboBox)
{
string[] strings = new string[mComboBox.Items.Count];
for (int i = 0; i < mComboBox.Items.Count; i++)
{
strings[i] = mComboBox.Items[i].ToString();
}
return strings;
}
public static void AddStringsToListView(ListView mListView, string[] strings)
{
mListView.Items.Clear();
for (int i = 0; i < strings.Length; i++)
{
mListView.Items.Add(strings[i]);
}
}
#endregion
///
/// 从SYGOLE获取的数据转换函数
///
public class Tool
{
//将十六进制的字符串转化为ushort
public static ushort HexString2Ushort(string s)
{
ushort value = 0;
for (int i = 0; i < s.Length; i++)
{
if (s[i] != ' ')
{
value = (ushort)(value * 16 + HexStringToHex(s, i));
}
}
return value;
}
//将字节数组形式的mac地址转化为对应的字符串
public static string MacToString(byte[] mac)
{
string macString = "";
for (int i = 0; i < 6; i++)
{
macString += ByteToHexString(mac[i]);
if (i < 5)
{
macString += ":";
}
}
return macString;
}
//将字符串形式的mac地址转化为对应的字节数组
public static byte[] StringToMac(string str)
{
string temp = "";
for (int i = 0; i < str.Length; i++)
{
if ((str[i] != ' ') && (str[i] != ':'))
{
temp += str[i];
}
}
return HexStringToByte(temp, 0, 6); //6字节长度
}
//判断字符串是否是十六进制字符串
public static bool ValidHexString(string str)
{
for (int i = 0; i < str.Length; i++)
{
if (!
(((str[i] >= '0') && (str[i] <= '9')) ||
((str[i] >= 'a') && (str[i] <= 'f')) ||
((str[i] >= 'A') && (str[i] <= 'F')))
)
{
return false;
}
}
return true;
}
private static string GetStringWithoutSpace(string str, int pos)
{
string temp = "";
for (int i = pos; i < str.Length; i++)
{
if ((str[i] != ' ') && (str[i] != ':'))
{
temp += str[i];
}
}
return temp;
}
//将单个十六进制字符(4 bits)转化为byte
private static byte HexStringToHex(string str, int pos)
{
byte value = 0;
if ((str[pos] >= '0') && (str[pos] <= '9'))
{
value = (byte)(str[pos] - '0');
}
else if ((str[pos] >= 'a') && (str[pos] <= 'f'))
{
value = (byte)(str[pos] - 'a' + 10);
}
else if ((str[pos] >= 'A') && (str[pos] <= 'F'))
{
value = (byte)(str[pos] - 'A' + 10);
}
return value;
}
//将字符串的pos位置开始,转化为数组,转化后数组的长度为cnt
public static byte[] HexStringToByte(string str, int pos, int cnt)
{
if ((!ValidHexString(str)) || ((str.Length - pos) >> 1 < cnt))
{
return null;
}
byte[] data = new byte[cnt];
for (int i = 0; i < cnt; i++)
{
data[i] = (byte)(HexStringToHex(str, 2 * i + pos) * 16 + HexStringToHex(str, 2 * i + pos + 1));
}
return data;
}
public static string Bytes2String(byte[] data, int offset, int len)
{
string outString = "";
for (int i = offset; i < len + offset; i++)
{
outString += (char)data[i];
}
return outString;
}
//将字符串的pos位置开始,转化为数组,转化后数组的长度为cnt
public static byte[] HexStringToByte(string str, int pos)
{
string tempStr = GetStringWithoutSpace(str, pos);
return HexStringToByte(tempStr, 0, tempStr.Length >> 1);
}
public static byte HexStringToSingleByte(string str, int pos)
{
byte temp = 0;
int len = 2;
string tempStr = GetStringWithoutSpace(str, pos);
if (tempStr.Length == 0)
{
return 0;
}
else if (tempStr.Length < 2)
{
len = tempStr.Length;
}
else
{
len = 2;
}
for (int i = 0; i < len; i++)
{
temp = (byte)(temp * 16 + HexStringToHex(tempStr, i));
}
return temp;
}
//将字符串的pos位置开始,转化int
public static int HexStringToInt(string s, int pos)
{
string str = "";
int len = (s.Length - pos) > 8 ? 8 : s.Length - pos;
for (int i = pos; i < len; i++)
{
str += s[i];
}
for (int i = len; i < 8; i++)
{
str = "0" + str;
}
if (!ValidHexString(str))
{
return 0;
}
int result = 0;
byte[] data = HexStringToByte(str, 0, 4);
for (int i = 0; i < 4; i++)
{
result = (result << 8) + data[i];
}
return result;
}
//将字节类型的数据转化为十六进制字符串
public static string ByteToHexString(byte data)
{
string outString = "";
if (data < 16)
{
outString += "0";
}
outString += data.ToString("X");
return outString;
}
//将字节类型的数据转化为十六进制字符串
public static string ByteToHexString(byte[] data, int pos, int length, string space)
{
string outString = "";
for (int i = pos; i < pos + length; i++)
{
outString += ByteToHexString(data[i]);
if (i != pos + length - 1)
{
outString += space;
}
}
return outString;
}
//将ushort类型的数据转化为十六进制字符串
public static string UshortToHexString(ushort[] data, int pos, int length)
{
string outString = "";
for (int i = pos; i < pos + length; i++)
{
outString += ByteToHexString((byte)(data[i] >> 8));
outString += ByteToHexString((byte)(data[i] & 0xFF));
}
return outString;
}
}
//==========================================================================================
public class MyConvert
{
//string a = Convert.ToString(5, 2);
//string b = Convert.ToString(11, 8);
//string c = Convert.ToString(11, 16);
//int aa = Convert.ToInt32("101", 2);//二进制转换10进制
//int bb = Convert.ToInt32("13", 8); //八进制转换10进制
//int cc = Convert.ToInt32("b", 16); //十六进制转换10进制
#region C++转换程序(C#里面有完整的转换函数)
//十进制转二制
public static string DtoB(int d)
{
//Console.WriteLine(Convert.ToString(5,2))
string str = "";
//判断该数如果小于2,则直接输出
if (d < 2)
{
str = d.ToString();
}
else
{
int c;
int s = 0;
int n = d;
while (n >= 2)
{
s++;
n = n / 2;
}
int[] m = new int[s];
int i = 0;
do
{
c = d / 2;
m[i++] = d % 2;
d = c;
} while (c >= 2);
str = d.ToString();
for (int j = m.Length - 1; j >= 0; j--)
{
str += m[j].ToString();
}
}
return str;
}
//十进制转八进制
public static string DtoO(int d)
{
string o = "";
if (d < 8)
{
o = d.ToString();
}
else
{
int c;
int s = 0;
int n = d;
int temp = d;
while (n >= 8)
{
s++;
n = n / 8;
}
int[] m = new int[s];
int i = 0;
do
{
c = d / 8;
m[i++] = d % 8;
d = c;
} while (c >= 8);
o = d.ToString();
for (int j = m.Length - 1; j >= 0; j--)
{
o += m[j];
}
}
return o;
}
//十进制转十六进制
public static string DtoX(int d)
{
string x = "";
if (d < 16)
{
x = Chang(d);
}
else
{
int c;
int s = 0;
int n = d;
int temp = d;
while (n >= 16)
{
s++;
n = n / 16;
}
string[] m = new string[s];
int i = 0;
do
{
c = d / 16;
m[i++] = Chang(d % 16); //判断是否大于10,如果大于10,则转换为A~F的格式
d = c;
} while (c >= 16);
x = Chang(d);
for (int j = m.Length - 1; j >= 0; j--)
{
x += m[j];
}
}
return x;
}
//判断是否为10~15之间的数,如果是则进行转换
public static string Chang(int d)
{
string x = "";
switch (d)
{
case 10:
x = "A";
break;
case 11:
x = "B";
break;
case 12:
x = "C";
break;
case 13:
x = "D";
break;
case 14:
x = "E";
break;
case 15:
x = "F";
break;
default:
x = d.ToString();
break;
}
return x;
}
public static int XtoD(string instr)
{
int i = Convert.ToInt32("FF", 16); //十六进制转换10进制
int j = Convert.ToInt32("1100", 2);
int k = Convert.ToInt32("12", 8);
return i;
}
#endregion
}
}
//==================================================================================================TcpBase
///
/// 网络通讯通用类函数库
///
class TcpBase
{
///
/// 用CMD命令测试网络连接状态
///
/// IP地址或网址
/// Ping结果 连接;超时或其他结果表示未连接
public static string CmdPing(string strIp)
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardInput.WriteLine("ping -n 1 " + strIp);
p.StandardInput.WriteLine("exit");
string strRst = p.StandardOutput.ReadToEnd();
string pingRst = "";
if (strRst.Contains("(0% loss)") || strRst.Contains("(0% 丢失)"))
pingRst = "连接";
else if (strRst.Contains("Request timed out") || strRst.Contains("请求超时"))
pingRst = "超时";
else if (strRst.Contains("Unknown host") || strRst.Contains("无法解析主机"))
pingRst = "无法解析主机";
else if (strRst.Contains("请求找不到主机"))
pingRst = "请求找不到主机";
else if (strRst.Contains("Destination host unreachable."))
pingRst = "无法到达目的主机";
else
pingRst = strRst;
p.Close();
return pingRst;
}
}
//==================================================================================================MyMath
///
/// 数学函数库(算法)
///
class MyMath
{
public static double GetMax(double[] datas)
{
double max = -9999;
try
{
if (datas.Length == 1)
return datas[0];
for (int i = 0; i < datas.Length; i++)
{
max = Math.Max(datas[i], max);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return max;
}
public static double GetMin(double[] datas)
{
double min = 9999;
try
{
if (datas.Length == 1)
return datas[0];
for (int i = 0; i < datas.Length; i++)
{
min = Math.Min(datas[i], min);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return min;
}
///
/// 获取PLC读取地址数据(从起始地址偏移)
///
/// 数据数组
/// PLC读取地址,从0开始
/// 返回整形数据或-1
public static int GetPlcData(byte[] byteData, int dataAddr)
{
try
{
if (byteData == null)
{
return -1;
}
if (byteData.Length < 10 + dataAddr * 2)
{
return -1;
}
else
{
int bitH = dataAddr * 2 + 9;
int bitL = dataAddr * 2 + 10;
return byteData[bitH] * 256 + byteData[bitL];
}
}
catch
{
return -1;
}
}
///
/// 获取PLC读取地址数据(从起始地址偏移)
///
/// 数据数组
/// PLC读取地址
/// PLC读取起始地址
/// 返回整形数据或-1
public static int GetPlcData(byte[] byteData, int dataAddr, int startAddr)
{
try
{
if (byteData == null)
{
return -1;
}
if (startAddr > dataAddr)
{
//MessageBox.Show("错误:要读取的数据小于起始地址");
return -1;
}
if (byteData.Length < 9 + (dataAddr - startAddr) * 2)
{
return -1;
}
else
{
int bitH = (dataAddr - startAddr) * 2 + 9;
int bitL = (dataAddr - startAddr) * 2 + 10;
return byteData[bitH] * 256 + byteData[bitL];
}
}
catch
{
//MessageBox.Show("Catch错误:" + ex.Message);
return -1;
}
}
///
/// 获取字节的某一位
///
/// 从0开始
///
public static bool GetPlcBit(int data, int index)
{
switch (index)
{
case 0:
return (data & 0x0001) > 0;
case 1:
return (data & 0x0002) > 0;
case 2:
return (data & 0x0004) > 0;
case 3:
return (data & 0x0008) > 0;
case 4:
return (data & 0x0010) > 0;
case 5:
return (data & 0x0020) > 0;
case 6:
return (data & 0x0040) > 0;
case 7:
return (data & 0x0080) > 0;
case 8:
return (data & 0x0100) > 0;
case 9:
return (data & 0x0200) > 0;
case 10:
return (data & 0x0400) > 0;
case 11:
return (data & 0x0800) > 0;
case 12:
return (data & 0x1000) > 0;
case 13:
return (data & 0x2000) > 0;
case 14:
return (data & 0x4000) > 0;
case 15:
return (data & 0x8000) > 0;
default:
return false;
}
}
public static bool GetPlcBitH2Low(int data, int index)
{
switch (index)
{
case 0:
return (data & 0x0100) > 0;
case 1:
return (data & 0x0200) > 0;
case 2:
return (data & 0x0400) > 0;
case 3:
return (data & 0x0800) > 0;
case 4:
return (data & 0x1000) > 0;
case 5:
return (data & 0x2000) > 0;
case 6:
return (data & 0x4000) > 0;
case 7:
return (data & 0x8000) > 0;
case 8:
return (data & 0x0001) > 0;
case 9:
return (data & 0x0002) > 0;
case 10:
return (data & 0x0004) > 0;
case 11:
return (data & 0x0008) > 0;
case 12:
return (data & 0x0010) > 0;
case 13:
return (data & 0x0020) > 0;
case 14:
return (data & 0x0040) > 0;
case 15:
return (data & 0x0080) > 0;
default:
return false;
}
}
///
/// 获取字节的某一位
///
/// 从0开始
///
public static bool GetPlcBit(byte[] byteData, int dataAddr, int index, int startAddr)
{
int value = GetPlcData(byteData, dataAddr, startAddr);
bool bResult = GetPlcBit(value, index);
return bResult;
}
public static bool GetPlcBitH2Low(byte[] byteData, int dataAddr, int index, int startAddr)
{
int value = GetPlcData(byteData, dataAddr, startAddr);
bool bResult = GetPlcBitH2Low(value, index);
return bResult;
}
///
/// 获取单精度浮点数(float)数据
///
/// PLC读取总数据
/// 获取数据的地址
/// PLC起始地址
/// 数据正反序
///
public static float GetPlcSingle(byte[] byteData, int dataAddr, int startAddr, bool positiveSequence = true)
{
try
{
if (byteData == null)
{
return -1;
}
if (startAddr > dataAddr)
{
return -1;
}
if (byteData.Length < 9 + (dataAddr - startAddr) * 2)
{
return -1;
}
else
{
float result = -1;
int startBit = (dataAddr - startAddr) * 2 + 9;
byte[] arrLength = new byte[4];
arrLength[0] = byteData[startBit + 0];
arrLength[1] = byteData[startBit + 1];
arrLength[2] = byteData[startBit + 2];
arrLength[3] = byteData[startBit + 3];
if (positiveSequence)
{
result = BitConverter.ToSingle(arrLength, 0);
}
else
{
result = BitConverter.ToSingle(arrLength.Reverse().ToArray(), 0);
}
result = Convert.ToSingle(Math.Round(result, 3));
return result;
}
}
catch
{
return -1;
}
}
///
/// 获取字符串(string)
///
/// PLC读取总数据
/// 获取数据的地址
/// PLC起始地址
/// 读取的地址数量(单位16)
/// 数据正反序
/// 转换为字符串类型,2=二进制,10=十进制,16=十六进制,其他=char字符串
///
public static string GetPlcString(byte[] byteData, int dataAddr, int startAddr, int dataNum,
bool positiveSequence = true, int strType = 0)
{
string result = "";
try
{
if (byteData == null)
{
return result;
}
if (startAddr > dataAddr + dataNum)
{
return result;
}
if (byteData.Length < 9 + (dataAddr - startAddr) * 2)
{
return result;
}
else
{
int startBit = (dataAddr - startAddr) * 2 + 9;
byte[] arrLength = new byte[dataNum * 2];
for (int i = 0; i < dataNum * 2; i++)
{
arrLength[i] = byteData[startBit + i];
}
if (!positiveSequence)
{
arrLength = (byte[])arrLength.Reverse();
}
switch (strType)
{
case 2:
foreach (byte b in arrLength)
{
result += ConvertBase.MyConvert.DtoB(b);
}
break;
case 10:
foreach (byte b in arrLength)
{
result += b.ToString();
}
break;
case 16:
foreach (byte b in arrLength)
{
result += b.ToString("X2");
}
break;
default:
foreach (byte b in arrLength)
{
result += Convert.ToChar(b).ToString();
}
break;
}
return result.Trim();
}
}
catch
{
return result;
}
}
//======================================================================
///
/// 字节数组(byte 8位)转化为ushort(16位)数组
///
public static ushort[] GetushortsFromValue(byte[] value)
{
ushort[] rtnValues;
byte[] bytes = value;
int length = bytes.Length / 2;
if (bytes.Length % 2 == 0)
{
rtnValues = new ushort[length];
for (int i = 0; i < bytes.Length; i += 2)
{
rtnValues[i / 2] = BitConverter.ToUInt16(bytes, i);
}
}
else
{
rtnValues = new ushort[bytes.Length / 2 + 1];
for (int i = 0; i < bytes.Length - 1; i += 2)
{
rtnValues[i / 2] = BitConverter.ToUInt16(bytes, i);
}
rtnValues[bytes.Length / 2] = bytes[bytes.Length - 1];
}
return rtnValues;
}
///
/// 字符串(string)转化为ushort(16位)数组
///
public static ushort[] GetushortsFromValue(string value)
{
byte[] bytes = System.Text.Encoding.Default.GetBytes(value);
ushort[] ushorts = GetushortsFromValue(bytes);
return ushorts;
}
///
/// 单精度小数(float 32位)转化为ushort(16位)数组
///
public static ushort[] GetushortsFromValue(float value)
{
byte[] bytes = BitConverter.GetBytes(value);
ushort[] ushorts = GetushortsFromValue(bytes);
return ushorts;
}
///
/// 双精度小数(double 64位)转化为ushort(16位)数组
///
public static ushort[] GetushortsFromValue(double value)
{
byte[] bytes = BitConverter.GetBytes(value);
ushort[] ushorts = GetushortsFromValue(bytes);
return ushorts;
}
//======================================================================
///
/// 字节数组(byte 8位)转化为short(16位)数组
///
public static short[] GetshortsFromValue(byte[] value)
{
short[] rtnValues;
byte[] bytes = value;
int length = bytes.Length / 2;
if (bytes.Length % 2 == 0)
{
rtnValues = new short[length];
for (int i = 0; i < bytes.Length; i += 2)
{
rtnValues[i / 2] = BitConverter.ToInt16(bytes, i);
}
}
else
{
rtnValues = new short[bytes.Length / 2 + 1];
for (int i = 0; i < bytes.Length - 1; i += 2)
{
rtnValues[i / 2] = BitConverter.ToInt16(bytes, i);
}
rtnValues[bytes.Length / 2] = bytes[bytes.Length - 1];
}
return rtnValues;
}
///
/// 字符串(string)转化为short(16位)数组
///
public static short[] GetshortsFromValue(string value)
{
byte[] bytes = System.Text.Encoding.Default.GetBytes(value);
short[] shorts = GetshortsFromValue(bytes);
return shorts;
}
///
/// 整形(int 32位)转化为short(16位)数组
///
public static short[] GetshortsFromValue(int value)
{
byte[] bytes = BitConverter.GetBytes(value);
short[] shorts = GetshortsFromValue(bytes);
return shorts;
}
///
/// 单精度小数(float 32位)转化为short(16位)数组
///
public static short[] GetshortsFromValue(float value)
{
byte[] bytes = BitConverter.GetBytes(value);
short[] shorts = GetshortsFromValue(bytes);
return shorts;
}
///
/// 双精度小数(double 64位)转化为ushort(16位)数组
///
public static short[] GetshortsFromValue(double value)
{
byte[] bytes = BitConverter.GetBytes(value);
short[] shorts = GetshortsFromValue(bytes);
return shorts;
}
}
class CodeDfn
{
public const string BlankSpace = " ";
public const string StrEnter = "\r\n";
}
class PlcMath
{
#region S7协议数据处理(以字节为基础)
public static bool GetS7BoolBit(byte data, int index)
{
switch (index)
{
case 0: return (data & 0x01) > 0;
case 1: return (data & 0x02) > 0;
case 2: return (data & 0x04) > 0;
case 3: return (data & 0x08) > 0;
case 4: return (data & 0x10) > 0;
case 5: return (data & 0x20) > 0;
case 6: return (data & 0x40) > 0;
case 7: return (data & 0x80) > 0;
default: return false;
}
}
public static bool GetS7BoolData(byte[] byteData, int dataAddr, int startAddr, int index)
{
byte data = GetS7ByteData(byteData, dataAddr, startAddr);
return GetS7BoolBit(data, index);
}
///
/// 获取PLC读取地址数据(从起始地址偏移)
///
/// 数据数组
/// PLC读取地址
/// PLC读取起始地址
/// 返回整形数据或-1
public static byte GetS7ByteData(byte[] byteData, int dataAddr, int startAddr)
{
try
{
if (byteData == null)
{
return 0;
}
if (startAddr > dataAddr)
{
MessageBox.Show("错误:获取S7字节数据, 要读取的数据小于起始地址");
return 0;
}
if (byteData.Length < (dataAddr - startAddr))
{
MessageBox.Show("错误:获取S7字节数据, 要读取的偏移地址超出数组长度,偏移=" + (dataAddr - startAddr) + ", 数组长度=" +
byteData.Length);
return 0;
}
else
{
int bit = dataAddr - startAddr;
return byteData[bit];
}
}
catch
{
//MessageBox.Show("Catch错误:" + ex.Message);
return 0;
}
}
///
/// 获取PLC读取地址数据(从起始地址偏移)
///
/// 数据数组
/// PLC读取地址
/// PLC读取起始地址
/// 返回整形数据或-1
public static byte GetS7ByteData(byte[] byteData, int dataAddr)
{
try
{
if (byteData == null)
{
return 0;
}
if (byteData.Length < byteData.Length)
{
MessageBox.Show("获取S7字节数据,地址超出数组长度!", "警告");
return 0;
}
return byteData[dataAddr];
}
catch (Exception ex)
{
MessageBox.Show("Catch错误:获取S7字节数据" + ex.Message);
return 0;
}
}
public static int GetS7WordData(byte[] byteData, int dataAddr, int startAddr)
{
try
{
if (byteData == null)
{
return -1;
}
if (startAddr > dataAddr)
{
//MessageBox.Show("错误:要读取的数据小于起始地址");
return -1;
}
if (byteData.Length < (dataAddr - startAddr) * 2)
{
return -1;
}
else
{
//int bitH = (DataAddr - startAddr) * 2;
//int bitL = (DataAddr - startAddr) * 2 + 1;
int bitH = (dataAddr - startAddr);
int bitL = (dataAddr - startAddr) + 1;
return byteData[bitH] * 256 + byteData[bitL];
}
}
catch
{
//MessageBox.Show("Catch错误:" + ex.Message);
return -1;
}
}
///
/// 获取字符串(string)
///
/// PLC读取总数据
/// 获取数据的地址
/// PLC起始地址
/// 读取的地址数量(单位16)
/// 数据正反序
/// 转换为字符串类型,2=二进制,10=十进制,16=十六进制,其他=char字符串
///
public static string GetS7StringData(byte[] byteData, int dataAddr, int startAddr, int dataNum, int strType = 0,
bool positiveSequence = true)
{
string result = "";
try
{
if (byteData == null)
{
return result;
}
if (startAddr > dataAddr + dataNum)
{
return result;
}
if (byteData.Length < (dataAddr - startAddr))
{
return result;
}
else
{
int startBit = (dataAddr - startAddr);
byte[] arrLength = new byte[dataNum];
for (int i = 0; i < dataNum; i++)
{
arrLength[i] = byteData[startBit + i];
}
if (!positiveSequence)
{
arrLength = (byte[])arrLength.Reverse();
}
switch (strType)
{
case 2:
foreach (byte b in arrLength)
{
result += ConvertBase.MyConvert.DtoB(b);
}
break;
case 10:
foreach (byte b in arrLength)
{
result += b.ToString();
}
break;
case 16:
foreach (byte b in arrLength)
{
result += b.ToString("X2");
}
break;
default:
foreach (byte b in arrLength)
{
if (b >= 32)
result += Convert.ToChar(b).ToString();
}
break;
}
return result.Trim();
}
}
catch
{
return result;
}
}
#endregion
#region ModbusTCP/FinsTCP协议数据处理(以字为基础)
///
/// 获取PLC读取地址数据(从起始地址偏移)
///
/// 数据数组
/// PLC读取地址,从0开始
/// 返回整形数据或-1
public static int GetPlcData(byte[] byteData, int dataAddr)
{
try
{
if (byteData == null)
{
return -1;
}
if (byteData.Length < dataAddr * 2)
{
return -1;
}
else
{
int bitH = dataAddr * 2;
int bitL = dataAddr * 2 + 1;
return byteData[bitH] * 256 + byteData[bitL];
}
}
catch
{
return -1;
}
}
///
/// 获取PLC读取地址数据(从起始地址偏移)
///
/// 数据数组
/// PLC读取地址
/// PLC读取起始地址
/// 返回整形数据或-1
public static byte GetPlcByteData(byte[] byteData, int dataAddr, int startAddr)
{
try
{
if (byteData == null)
{
return 0;
}
if (startAddr > dataAddr)
{
//MessageBox.Show("错误:要读取的数据小于起始地址");
return 0;
}
//if (byteData.Length < (DataAddr - startAddr) * 2)
if (byteData.Length < (dataAddr - startAddr))
{
return 0;
}
else
{
int bit = dataAddr - startAddr;
return byteData[bit];
}
}
catch
{
//MessageBox.Show("Catch错误:" + ex.Message);
return 0;
}
}
///
/// 获取PLC读取地址数据(从起始地址偏移)
///
/// 数据数组
/// PLC读取地址
/// PLC读取起始地址
/// 返回整形数据或-1
public static int GetPlcData(byte[] byteData, int dataAddr, int startAddr)
{
try
{
if (byteData == null)
{
return -1;
}
if (startAddr > dataAddr)
{
//MessageBox.Show("错误:要读取的数据小于起始地址");
return -1;
}
if (byteData.Length < (dataAddr - startAddr) * 2)
{
return -1;
}
else
{
int bitH = (dataAddr - startAddr) * 2;
int bitL = (dataAddr - startAddr) * 2 + 1;
return byteData[bitH] * 256 + byteData[bitL];
}
}
catch
{
//MessageBox.Show("Catch错误:" + ex.Message);
return -1;
}
}
///
/// 获取字节的某一位
///
/// 从0开始
///
public static bool GetPlcBit(int data, int index)
{
switch (index)
{
case 0:
return (data & 0x0001) > 0;
case 1:
return (data & 0x0002) > 0;
case 2:
return (data & 0x0004) > 0;
case 3:
return (data & 0x0008) > 0;
case 4:
return (data & 0x0010) > 0;
case 5:
return (data & 0x0020) > 0;
case 6:
return (data & 0x0040) > 0;
case 7:
return (data & 0x0080) > 0;
case 8:
return (data & 0x0100) > 0;
case 9:
return (data & 0x0200) > 0;
case 10:
return (data & 0x0400) > 0;
case 11:
return (data & 0x0800) > 0;
case 12:
return (data & 0x1000) > 0;
case 13:
return (data & 0x2000) > 0;
case 14:
return (data & 0x4000) > 0;
case 15:
return (data & 0x8000) > 0;
default:
return false;
}
}
public static bool GetPlcBitH2Low(int data, int index)
{
switch (index)
{
case 0:
return (data & 0x0100) > 0;
case 1:
return (data & 0x0200) > 0;
case 2:
return (data & 0x0400) > 0;
case 3:
return (data & 0x0800) > 0;
case 4:
return (data & 0x1000) > 0;
case 5:
return (data & 0x2000) > 0;
case 6:
return (data & 0x4000) > 0;
case 7:
return (data & 0x8000) > 0;
case 8:
return (data & 0x0001) > 0;
case 9:
return (data & 0x0002) > 0;
case 10:
return (data & 0x0004) > 0;
case 11:
return (data & 0x0008) > 0;
case 12:
return (data & 0x0010) > 0;
case 13:
return (data & 0x0020) > 0;
case 14:
return (data & 0x0040) > 0;
case 15:
return (data & 0x0080) > 0;
default:
return false;
}
}
///
/// 获取字节的某一位
///
/// 从0开始
///
public static bool GetPlcBit(byte[] byteData, int dataAddr, int index, int startAddr)
{
int value = GetPlcData(byteData, dataAddr, startAddr);
bool bResult = GetPlcBit(value, index);
return bResult;
}
public static bool GetPlcBitH2Low(byte[] byteData, int dataAddr, int index, int startAddr)
{
int value = GetPlcData(byteData, dataAddr, startAddr);
bool bResult = GetPlcBitH2Low(value, index);
return bResult;
}
///
/// 获取单精度浮点数(float)数据
///
/// PLC读取总数据
/// 获取数据的地址
/// PLC起始地址
/// 数据正反序
///
public static float GetPlcSingle(byte[] byteData, int dataAddr, int startAddr, bool positiveSequence)
{
try
{
if (byteData == null)
{
return -1;
}
if (startAddr > dataAddr)
{
return -1;
}
if (byteData.Length < (dataAddr - startAddr))
{
return -1;
}
else
{
float result = -1;
int startBit = (dataAddr - startAddr);
byte[] arrLength = new byte[4];
arrLength[0] = byteData[startBit + 0];
arrLength[1] = byteData[startBit + 1];
arrLength[2] = byteData[startBit + 2];
arrLength[3] = byteData[startBit + 3];
if (positiveSequence)
{
result = BitConverter.ToSingle(arrLength, 0);
}
else
{
result = BitConverter.ToSingle(arrLength.Reverse().ToArray(), 0);
}
result = Convert.ToSingle(Math.Round(result, 3));
return result;
}
}
catch
{
return -1;
}
}
///
/// 获取字符串(string)
///
/// PLC读取总数据
/// 获取数据的地址
/// PLC起始地址
/// 读取的地址数量(单位16)
/// 数据正反序
/// 转换为字符串类型,2=二进制,10=十进制,16=十六进制,其他=char字符串
///
public static string GetPlcString(byte[] byteData, int dataAddr, int startAddr, int dataNum, int strType = 0,
bool positiveSequence = true)
{
string result = "";
try
{
if (byteData == null)
{
return result;
}
if (startAddr > dataAddr + dataNum)
{
return result;
}
if (byteData.Length < (dataAddr - startAddr) * 2)
{
return result;
}
else
{
int startBit = (dataAddr - startAddr) * 2;
byte[] arrLength = new byte[dataNum * 2];
for (int i = 0; i < dataNum * 2; i++)
{
arrLength[i] = byteData[startBit + i];
}
if (!positiveSequence)
{
arrLength = (byte[])arrLength.Reverse();
}
switch (strType)
{
case 2:
foreach (byte b in arrLength)
{
result += ConvertBase.MyConvert.DtoB(b);
}
break;
case 10:
foreach (byte b in arrLength)
{
result += b.ToString();
}
break;
case 16:
foreach (byte b in arrLength)
{
result += b.ToString("X2");
}
break;
default:
foreach (byte b in arrLength)
{
if (b >= 32)
result += Convert.ToChar(b).ToString();
}
break;
}
return result.Trim();
}
}
catch
{
return result;
}
}
#endregion
}
class Internet
{
public static bool IsIpReachable(string ipAddress)
{
try
{
Ping ping = new Ping();
PingReply reply = ping.Send(ipAddress);
return (reply.Status == IPStatus.Success);
}
catch (PingException)
{
// 发生 Ping 异常,IP 不可达
return false;
}
}
public static bool IsIpAddressValid(string ipAddress)
{
string pattern = @"^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
return Regex.IsMatch(ipAddress, pattern);
}
}
}