- 使用
ClipToBounds
属性
将 ClipToBounds
属性设置为 True
,这将会将超出的文本裁剪掉,不会显示出来。
复制<TextBox Text="这是一段很长很长很长很长的文本。" Width="100" ClipToBounds="True"/>
针对上面5项做特殊处理。
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Speech.Synthesis;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using WpfM20UpdateFW;
namespace FT_Tools
{
public class Externs
{
[DllImport("winspool.drv")]
public static extern bool SetDefaultPrinter(String Name); //调用win api将指定名称的打印机设置为默认打印机
}
public class LocalPrinter
{
private static PrintDocument fPrintDocument = new PrintDocument();
//获取本机默认打印机名称
public static String DefaultPrinter()
{
return fPrintDocument.PrinterSettings.PrinterName;
}
public static List<String> GetLocalPrinters()
{
List<String> fPrinters = new List<String>();
fPrinters.Add(DefaultPrinter()); //默认打印机始终出现在列表的第一项
foreach (String fPrinterName in PrinterSettings.InstalledPrinters)
{
if (!fPrinters.Contains(fPrinterName))
{
fPrinters.Add(fPrinterName);
}
}
return fPrinters;
}
}
class CRC32
{
private static ulong[] Crc32Table;
//生成CRC32码表
private static void GetCRC32Table()
{
ulong Crc;
Crc32Table = new ulong[256];
int i, j;
for (i = 0; i < 256; i++)
{
Crc = (ulong)i;
for (j = 8; j > 0; j--)
{
if ((Crc & 1) == 1)
Crc = (Crc >> 1) ^ 0xEDB88320;
else
Crc >>= 1;
}
Crc32Table[i] = Crc;
}
}
/// <summary>
/// 获取字符串的CRC32校验值
/// </summary>
/// <param name="strHex">十六进制字符串</param>
/// <returns>32位CRC十六进制字符串</returns>
public static string GetCRC32(string strHex)
{
//生成码表
GetCRC32Table();
strHex = strHex.Replace(" ", "");
byte[] buffer = FT_Tools.MySerialPort.hexConvertToByteArray(strHex);
ulong value = 0xffffffff;
int len = buffer.Length;
for (int i = 0; i < len; i++)
{
value = (value >> 8) ^ Crc32Table[(value & 0xFF) ^ buffer[i]];
}
//return value ^ 0xffffffff;
return String.Format("{0:X8}", value ^ 0xffffffff);
}
}
class MyAPI
{
public delegate void MyDel(string format);//声明一个自定义委托,相当于函数指针
public static SpeechSynthesizer speechSynthesizer = new System.Speech.Synthesis.SpeechSynthesizer();
public static void speech(string s,int Speech)
{
if (Speech>0)
{
if (Speech == 1) { speechSynthesizer.SpeakAsync(s); }
else { speechSynthesizer.Speak(s); }
}
}
public static int imeiCheck(MyDel Log, string IMEI)
{
if (IMEI.Length != 15) { Log("IMEI length is " +IMEI.Length + ",it should be 15."); return -15; }
if (!Regex.IsMatch(IMEI, @"^[0-9]*$")) { Log(IMEI + " It should be all numbers."); return -12; }
char check = GetIMEICheckDigit(IMEI.Substring(0,14));
if (check != IMEI.Last()) { Log(IMEI + " The last IMEI digit is " + IMEI.Last() + ",it should be " + check); return -11; }
return 0; //OK
}
public static char GetIMEICheckDigit(string imei) //生成imei校验位
{
int i;
int sum1 = 0, sum2 = 0, total = 0;
int temp = 0;
for (i = 0; i < 14; i++)
{
if ((i % 2) == 0)
{
sum1 = sum1 + imei[i] - '0';
}
else
{
temp = (imei[i] - '0') * 2;
if (temp < 10)
{
sum2 = sum2 + temp;
}
else
{
sum2 = sum2 + 1 + temp - 10;
}
}
}
total = sum1 + sum2;
if ((total % 10) == 0)
{
return '0';
}
else
{
return (char)(((total / 10) * 10) + 10 - total + '0');
}
}
//创建去扩展名的文件夹
public static string CreateDirectorybyFileName(string fileName)
{
string fileNameWithoutExtenstion = Path.GetFileNameWithoutExtension(fileName);
string path = AppDomain.CurrentDomain.BaseDirectory;//当前目录
if (!string.IsNullOrEmpty(path))
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
path += fileNameWithoutExtenstion;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
return path+"\\";
}
public static bool isExistsAlphabet(string str)
{
return Regex.Matches(str, "[a-zA-Z]").Count > 0;
}
//[DllImport("user32.dll")]
//public static extern int SendMessage(int hWnd, // handle to destination window
//uint Msg, // message
//int wParam, // first message parameter
//int lParam // second message parameter
//);
[DllImport("kernel32.dll", SetLastError = true)]
static extern int WriteProfileString(string lpszSection, string lpszKeyName, string lpszString);
[DllImport("gdi32")]
public static extern int AddFontResource(string lpFileName);
const int WM_FONTCHANGE = 0x001D;
const int HWND_BROADCAST = 0xffff;
/// <summary>
/// 写入文件
/// </summary>
/// <param name="Log"></param>
/// <param name="path">文件路径加路径</param>
/// <param name="content"></param>
/// <param name="append"></param>
/// <param name="isBin"></param>
/// <returns></returns>
public static bool WriteToFile(MyDel Log, string path, string content,bool append=false,bool isBin=false)
{
try
{
//string path = AppDomain.CurrentDomain.BaseDirectory;//当前目录
if (!string.IsNullOrEmpty(path))
{
//if (!Directory.Exists(path))
//{
// Directory.CreateDirectory(path);
//}
//path += DateTime.Now.ToString("yyyyMMdd");//日期文件夹
//if (!Directory.Exists(path))
//{
// Directory.CreateDirectory(path);
//}
//path += "\\"+fileName; //文件名
if (!File.Exists(path))
{
FileStream fs = File.Create(path);
fs.Close();
}
if (File.Exists(path))
{
if (isBin)
{
using (FileStream fs = new FileStream(path, append?FileMode.Append: FileMode.Create, FileAccess.Write))
{
byte[] byteArray = FT_Tools.MySerialPort.hexConvertToByteArray(content);
fs.Write(byteArray, 0, byteArray.Length);
}
}
else
{
using (StreamWriter sw = new StreamWriter(path, append, System.Text.Encoding.UTF8)) //System.Text.Encoding.Default
{
sw.Write(content);
}
}
return true;
}
}
}
catch (Exception e)
{
Log("错误 "+e.ToString());
return false;
}
return false;
}
/// <summary>
/// 计算指定文件的MD5值
/// </summary>
/// <param name="fileName">指定文件的完全限定名称</param>
/// <returns>返回值的字符串形式</returns>
public static String ComputeMD5(String fileName)
{
String hashMD5 = String.Empty;
//检查文件是否存在,如果文件存在则进行计算,否则返回空值
if (System.IO.File.Exists(fileName))
{
using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
//计算文件的MD5值
System.Security.Cryptography.MD5 calculator = System.Security.Cryptography.MD5.Create();
Byte[] buffer = calculator.ComputeHash(fs);
calculator.Clear();
//将字节数组转换成十六进制的字符串形式
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < buffer.Length; i++)
{
stringBuilder.Append(buffer[i].ToString("x2"));
}
hashMD5 = stringBuilder.ToString();
}//关闭文件流
}//结束计算
return hashMD5;
}//ComputeMD5
public static string ComputeMD5(byte[] buffer)
{
//计算文件的MD5值
System.Security.Cryptography.MD5 calculator = System.Security.Cryptography.MD5.Create();
Byte[] bArray = calculator.ComputeHash(buffer);
calculator.Clear();
StringBuilder stringBuilder = new StringBuilder();
foreach (byte b in bArray)
{
stringBuilder.Append(b.ToString("x2"));
}
//将字节数组转换成十六进制的字符串形式
//for (int i = 0; i < buffer.Length; i++)
//{
// stringBuilder.Append(bArray[i].ToString("X2"));
//}
return stringBuilder.ToString();
}
/// <summary>
/// 复制文件夹及文件
/// </summary>
/// <param name="sourceFolder">原文件路径</param>
/// <param name="destFolder">目标文件路径</param>
/// <returns></returns>
public static int CopyFolder(string sourceFolder, string destFolder)
{
try
{
//如果目标路径不存在,则创建目标路径
if (!System.IO.Directory.Exists(destFolder))
{
System.IO.Directory.CreateDirectory(destFolder);
}
//得到原文件根目录下的所有文件
string[] files = System.IO.Directory.GetFiles(sourceFolder);
foreach (string file in files)
{
string name = System.IO.Path.GetFileName(file);
string dest = System.IO.Path.Combine(destFolder, name);
System.IO.File.Copy(file, dest,true);//复制文件
}
//得到原文件根目录下的所有文件夹
string[] folders = System.IO.Directory.GetDirectories(sourceFolder);
foreach (string folder in folders)
{
string name = System.IO.Path.GetFileName(folder);
string dest = System.IO.Path.Combine(destFolder, name);
CopyFolder(folder, dest);//构建目标路径,递归复制文件
}
return 1;
}
catch (Exception e)
{
MessageBox.Show(e.Message);
return 0;
}
}//copy folder
/// <summary>
/// 启动外部.exe应用
/// </summary>
/// <param name="exeName"></param>
public static void Exec(string exeName)
{
try
{
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = exeName;
info.Arguments = "";
info.WindowStyle = ProcessWindowStyle.Normal;
Process pro = Process.Start(info);
//pro.WaitForExit();
}
catch (System.Exception e)
{
MessageBox.Show("错误:" + e.ToString());
}
}
/// <summary>
/// 结束进程
/// </summary>
/// <param name="processName">exe的进程名,不是文件名</param>
public static void killProcess(string processName)
{
try {
Process[] allProgresse = System.Diagnostics.Process.GetProcessesByName(processName);
foreach (Process closeProgress in allProgresse)
{
if (closeProgress.ProcessName.Equals(processName))
{
closeProgress.Kill();
closeProgress.WaitForExit();
}
}
} catch { }
}
public static string RunCmd(string cmd)
{
using (Process proc = new Process())
{
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
proc.StandardInput.WriteLine(cmd);
proc.StandardInput.WriteLine("exit");
string outStr = proc.StandardOutput.ReadToEnd();
proc.Close();
return outStr;
}
}
public static byte[] readFile(MyDel Log,string fileName)
{
if (File.Exists(fileName))
{
using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
return buffer;
}//关闭文件流
}
Log("Not found file:"+fileName);
return null;
}
//sn后面有几位是流水号,按新规则
public static int getRightDigit(string sn)
{
int rightDigit = 5;
if (sn.Length < 5) { rightDigit = sn.Length; }
else
{
string sn45 = sn.Substring(sn.Length - 5, 2).ToLower();
rightDigit = (isContainLowercaseletters(sn45) ? 3 : 5); //流水号位数 sn倒数第4位或第5位有字母,可能是试产 2字母+3数字流水号;否则认为后5位为数字流水号
}
return rightDigit;
}
//是否包含小写字母
public static bool isContainLowercaseletters(string sn)
{
foreach (char c in sn)
{
if (c > 96 && c < 123)
{
return true;
}
}
return false;
}
[DllImport("kernel32.dll")]
public static extern int WinExec(string exeName, int operType);
public static childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is childItem)
{
return (childItem)child;
}
else
{
childItem childOfChild = FindVisualChild<childItem>(child);
if (childOfChild != null)
return childOfChild;
}
}
return null;
}
//按控件名 获得ListBox中的控件
public static object getControl(ListBox myListBox,int index,string FindName)
{
try
{
//var el = myListBox.ItemContainerGenerator.ContainerFromItem(myListBox.Items.GetItemAt(index)) as ListBoxItem;
//if (el != null && el is ListBoxItem)
//{
// ListBoxItem myListBoxItem = (ListBoxItem)el;
// ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(myListBoxItem);
// DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
// return myDataTemplate.FindName(FindName, myContentPresenter);
//}
ListBoxItem myListBoxItem = (ListBoxItem)(myListBox.ItemContainerGenerator.ContainerFromItem(myListBox.Items.GetItemAt(index)));
// Getting the currently selected ListBoxItem
// Note that the ListBox must have
// IsSynchronizedWithCurrentItem set to True for this to work
// ListBoxItem myListBoxItem = (ListBoxItem)(myListBox.ItemContainerGenerator.ContainerFromItem(myListBox.Items.CurrentItem));
// Getting the ContentPresenter of myListBoxItem
ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(myListBoxItem);
// Finding textBlock from the DataTemplate that is set on that ContentPresenter
DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
//TextBlock myTextBlock = (TextBlock)myDataTemplate.FindName("textBlock", myContentPresenter);
// Do something to the DataTemplate-generated TextBlock
//MessageBox.Show("The text of the TextBlock of the selected list item: " + myTextBlock.Text);
return myDataTemplate.FindName(FindName, myContentPresenter);
// BindingSettingsClass o = (BindingSettingsClass)(myListBox.Items.GetItemAt(i));
}
catch { }
return null;
}
}
}
using FT_Tools;
using MSFramework.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
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.Shapes;
using WpfM20UpdateFW;
namespace WpfDownloadTool
{
/// <summary>
/// SettingsWindow.xaml 的交互逻辑
/// </summary>
public partial class SettingsWindow : Window
{
List<BindingSettingsClass> bindingSettingsList = new List<BindingSettingsClass>();
public SettingsWindow()
{
InitializeComponent();
List<IniFile.IniData> config = IniFile.ReadAll();
foreach (IniFile.IniData k in config)
{
bindingSettingsList.Add(new BindingSettingsClass() { Name = k.name, Value = k.value, Describe = k.descripe });
}
myListBox.ItemsSource = bindingSettingsList;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
try {
for (int i = 0; i < myListBox.Items.Count; i++)//特殊的处理一下
{
BindingSettingsClass o = (BindingSettingsClass)(myListBox.Items.GetItemAt(i));
if (o.Name.Equals("SP"))
{
TextBox name = (TextBox)MyAPI.getControl(myListBox, i, "TextBoxValue");//得到控件
name.Visibility = Visibility.Hidden;
ComboBox sp = (ComboBox)MyAPI.getControl(myListBox, i, "ComboBoxSelect");
sp.Items.Add("0_Close");
sp.Items.Add("1_1902");
sp.Items.Add("2_1902T");
sp.Items.Add("3_Max332555");
sp.SelectionChanged += Sp_SelectionChanged;
sp.SelectedIndex = int.Parse(o.Value);
sp.Visibility = Visibility.Visible;
}
else if (o.Name.Equals("AP"))
{
TextBox name = (TextBox)MyAPI.getControl(myListBox, i, "TextBoxValue");//得到控件
name.Visibility = Visibility.Hidden;
ComboBox ap = (ComboBox)MyAPI.getControl(myListBox, i, "ComboBoxSelect");
ap.Items.Add("0_Close");
ap.Items.Add("1_F200");
ap.Items.Add("2_F600");
ap.Items.Add("3_F100");
ap.Items.Add("4_F210 F200-A");
ap.SelectionChanged += Ap_SelectionChanged;
ap.SelectedIndex = int.Parse(o.Value);
ap.Visibility = Visibility.Visible;
}
else if (o.Name.Equals("AP_File"))
{
Button buttonSP = (Button)MyAPI.getControl(myListBox, i, "ButtonSelect");
buttonSP.Visibility = Visibility.Visible;
buttonSP.Click += Button_Click_ap;
}
else if (o.Name.Equals("SP_SigFile"))
{
Button buttonSP = (Button)MyAPI.getControl(myListBox, i, "ButtonSelect");
buttonSP.Visibility = Visibility.Visible;
buttonSP.Click += Button_Click_sp_sig;
}
else if (o.Name.Equals("SP_RSAKeyFile"))
{
Button buttonSP = (Button)MyAPI.getControl(myListBox, i, "ButtonSelect");
buttonSP.Visibility = Visibility.Visible;
buttonSP.Click += Button_Click_sp_rsa;
}
}
} catch (Exception e2) { MessageBox.Show(e2.StackTrace); }
}
//根据名字,获取绑定的对象
private BindingSettingsClass getBindingItem(string name)
{
for (int i = 0; i < myListBox.Items.Count; i++)//特殊的处理一下
{
BindingSettingsClass o = (BindingSettingsClass)(myListBox.Items.GetItemAt(i));
if (o.Name.Equals(name))
{
return o;
}
}
MessageBox.Show("Can not find BindingSettingsItem by "+name);
return null;
}
private void Sp_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBox c = (ComboBox)sender;
int index=c.SelectedIndex;
string cText=c.Items.GetItemAt(c.SelectedIndex).ToString();
for (int i = 0; i < myListBox.Items.Count; i++)//特殊的处理一下
{
BindingSettingsClass o = (BindingSettingsClass)(myListBox.Items.GetItemAt(i));
if (o.Name.Equals("SP"))
{
o.Value = cText.Substring(0,1);
return;
}
}
}
private void Ap_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBox c = (ComboBox)sender;
int index = c.SelectedIndex;
string cText = c.Items.GetItemAt(c.SelectedIndex).ToString();
for (int i = 0; i < myListBox.Items.Count; i++)//特殊的处理一下
{
BindingSettingsClass o = (BindingSettingsClass)(myListBox.Items.GetItemAt(i));
if (o.Name.Equals("AP"))
{
if (cText.Equals("")) { return; }
o.Value = cText.Substring(0, 1);
return;
}
}
}
private void Button_Click_ap(object sender, RoutedEventArgs e)
{
BindingSettingsClass ap = getBindingItem("AP");
if (ap == null) { return; }
var openFileDialog = new Microsoft.Win32.OpenFileDialog();
if (ap.Value.Equals("1") || ap.Value.Equals("2")) { openFileDialog.Filter = "F200 F600 AP|*.mbn|F100 AP|*.txt|F210 F200-A AP|*.pac"; }
else if (ap.Value.Equals("3")) { openFileDialog.Filter = "F100 AP|*.txt|F200 F600 AP|*.mbn|F210 F200-A AP|*.pac"; }
else if (ap.Value.Equals("4")) { openFileDialog.Filter = "F210 F200-A AP|*.pac|F200 F600 AP|*.mbn|F100 AP|*.txt"; }
else { openFileDialog.Filter = "F200 F600 AP|*.mbn|F100 AP|*.txt|F210 F200-A AP|*.pac"; }//只是换顺序
openFileDialog.Multiselect = false;
if (openFileDialog.ShowDialog() == true)
{
Log("AP_File=" + openFileDialog.FileName);
BindingSettingsClass o = getBindingItem("AP_File");
if (o == null) { return; }
o.Value = openFileDialog.FileName;
}
}
private void Button_Click_sp_sig(object sender, RoutedEventArgs e)
{
BindingSettingsClass o = getBindingItem("SP_SigFile");
if (o == null) { return; }
BindingSettingsClass ap = getBindingItem("AP");
if (ap == null) { return; }
BindingSettingsClass sp = getBindingItem("SP");
if (sp == null) { return; }
if (sp.Value.Equals("3"))
{
//文件夹
var dialog = new System.Windows.Forms.FolderBrowserDialog()
{
Description = "Please select SP File path"
};
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Log("SP_SigFile=" + dialog.SelectedPath);
o.Value = dialog.SelectedPath;
}
}
else
{
var openFileDialog = new Microsoft.Win32.OpenFileDialog();
if (sp.Value.Equals("1") && ap.Value.Equals("3")) { openFileDialog.Filter = "F100 SP|*.hex|SP File|*.SIG"; }//F100 1902
else { openFileDialog.Filter = "SP File|*.SIG|F100 SP|*.hex"; }
openFileDialog.Multiselect = false;
if (openFileDialog.ShowDialog() == true)
{
Log("SP_SigFile=" + openFileDialog.FileName);
o.Value = openFileDialog.FileName;
}
}
}
private void Button_Click_sp_rsa(object sender, RoutedEventArgs e)
{
BindingSettingsClass spKey = getBindingItem("SP_RSAKeyFile");
if (spKey == null) { return; }
BindingSettingsClass ap = getBindingItem("AP");
if (ap == null) { return; }
BindingSettingsClass sp = getBindingItem("SP");
if (sp == null) { return; }
if (ap.Value.Equals("3") && sp.Value.Equals("1")) { spKey.Value = ""; MessageBox.Show("F100 SP1902 key should be empty."); return; }
if (sp.Value.Equals("3"))
{
//文件夹
var dialog = new System.Windows.Forms.FolderBrowserDialog()
{
Description = "Please select SP Key File path"
};
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
spKey.Value = dialog.SelectedPath;
}
}
else
{
var openFileDialog = new Microsoft.Win32.OpenFileDialog()
{
Filter = "SP File|*.RSA",
Multiselect = false
};
if (openFileDialog.ShowDialog() == true)
{
spKey.Value = openFileDialog.FileName;
}
}
}
private void Log(string s)
{ }
}
}