zoukankan      html  css  js  c++  java
  • 完美世界自动更新程序

     
     应用程序:链接:http://pan.baidu.com/s/1nt9dP49 密码:eehd
     说明
    本程序 是c#写的用的.net 3.5,
    本程序要操作系统要win7以上的,
    
    XP系统无法运行
    
    把本程序 复制到游戏的目录下
    
    1 如何打补丁文件
       补丁的目录要和游戏的目录是一致的,补丁的文件类型必须为.7Z格式的文件名建议使用英文
       如wmgjUpdate.7z,请使用专业的7Z打包工具打包。
       
        
    2 如何让程序自动更新补丁 
      将服务器的上更新版本号设置大于本地的 更新版本号则自动更新(更新版本号为整型数字)
     要确保 “版本验证文件”的“客户端补丁地址” 链接是有效的 无否无法自动更新
     
    3 网址格式 
    网页的格式这样是对的  http://www.baidu.com/
    这样是错的 www.baidu.com
    说明
     

     



    MainWindow.xaml
    <UserControl x:Class="WpfApplication1.ImageButton"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
                 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
                 mc:Ignorable="d" Height="28.654" Width="83.385">
        <Grid>
            <Image x:Name="image1" HorizontalAlignment="Left" Height="29" VerticalAlignment="Top" Width="84" Margin="-0.125,0,0,0" Source="Images/button-bg.png" Stretch="UniformToFill" MouseLeave="image1_MouseLeave" MouseMove="image1_MouseMove" MouseUp="image1_MouseUp" MouseLeftButtonUp="image1_MouseLeftButtonUp" MouseLeftButtonDown="image1_MouseLeftButtonDown"/>
            <Label x:Name="label1" Content="按钮1"  FontFamily="FangSong" Height="29"  HorizontalContentAlignment="Center" Margin="-0.125,0,0,0" VerticalAlignment="Top" Width="84" MouseLeave="image1_MouseLeave" MouseMove="image1_MouseMove" MouseUp="image1_MouseUp" MouseLeftButtonUp="image1_MouseLeftButtonUp" MouseLeftButtonDown="image1_MouseLeftButtonDown" HorizontalAlignment="Left" FontSize="14">
                <Label.Foreground>
                    <SolidColorBrush Color="#FFB3D0E9"/>
                </Label.Foreground>
            </Label>
        </Grid>
    </UserControl>
     

    MainWindow.xaml.CS
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    using IniFilesClass;
    using SevenZip;
    namespace WpfApplication1
    {
        /// <summary>
        /// MainWindow.xaml 的交互逻辑
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
                WpfApplication.ThreadClass.ExecuteRunOnceThread();
            }
            #region 常用变量
            private string updateTmpFolder;
            private string updateFileName;
            #endregion
            #region 操作 INI Files ...
            public string homePageUrl;
            public string bBsPageUrl;
            public string serverPageUrl;
            public string registerPageUrl;
            public string changePasswdUrl;
            public string loaderMainPageUrl;
            public string VersionCheckUrl;
            public string ClientUpdateDatakUrl;
            public int updateVersionNumber;
            public int newestVersionNumber;
            public string updateTips;
            public bool debugMode;
            public string IniFileName;
            public string newestIniFileName;
            private void WriteConfig()
            {
            }
            private void ReadConfig()
            {
                IniFileName = AppDomain.CurrentDomain.BaseDirectory + "patcher.ini";
                IniFile ini;
                ini = new IniFile(IniFileName);
                homePageUrl = ini.ReadString("网页""官方网站""");
                bBsPageUrl = ini.ReadString("网页""官方论坛""");
                serverPageUrl = ini.ReadString("网页""客服中心""");
                registerPageUrl = ini.ReadString("网页""注册帐号""");
                changePasswdUrl = ini.ReadString("网页""密码修改""");
                loaderMainPageUrl = ini.ReadString("网页""登陆器主页""");
                VersionCheckUrl = ini.ReadString("文件""版本验证文件""");
                updateVersionNumber = ini.ReadInteger("配置""更新版本号", -1);
                
                debugMode = ini.ReadBool("配置""调试模式"false);
            }
            /// <summary>
            /// 判断 patcher.ini文件是否存在
            /// </summary>
            private void CheckPatcherIniFileExists()
            {
                string patcherFileName = AppDomain.CurrentDomain.BaseDirectory + "\patcher.ini";
                if (!System.IO.File.Exists(patcherFileName))
                {
                    MessageBox.Show("patcher.ini 文件丢失,程序坚决不执行!""提示"MessageBoxButton.OK, MessageBoxImage.Information);
                    Environment.Exit(0);
                }
            }
            /// <summary>
            /// 创建文件夹 D:AdministratorDesktop完美世界国际版patcherhttp_update
            /// </summary>
            private void CreateUpdateTmpFolder()
            {
                updateTmpFolder = AppDomain.CurrentDomain.BaseDirectory + "patcher\http_update";
                if (!System.IO.Directory.Exists(updateTmpFolder))
                {
                    System.IO.Directory.CreateDirectory(updateTmpFolder);
                    System.IO.File.SetAttributes(updateTmpFolder, System.IO.FileAttributes.Hidden);
                }
            }
            private void GetNewestVersionNumber()
            {
                CreateUpdateTmpFolder();
                newestIniFileName = AppDomain.CurrentDomain.BaseDirectory + "patcher\http_update\patcher.ini";
                updateFileName = AppDomain.CurrentDomain.BaseDirectory + "patcher\http_update\wmsjUpdate.7z";
                IniFile ini2;
                ini2 = new IniFile(newestIniFileName);
                newestVersionNumber = ini2.ReadInteger("配置""更新版本号", -1);
                updateTips = ini2.ReadString("配置""备注""");
                ClientUpdateDatakUrl = ini2.ReadString("文件""客户端补丁地址""");
                //MessageBox.Show("最新版本号 :" + newestVersionNumber);
            }
            #endregion
            #region PNG图形界面 + Webbrowser ...
            webBrowserWindow1 window1 = new webBrowserWindow1();
            private void InitialWindow1()
            {
                try
                {
                    window1.webBrowser1.Navigate(new Uri(loaderMainPageUrl));
                }
                catch
                {
                    window1.webBrowser1.NavigateToString(
                                                         "<P align=center><FONT color=#ff0000>" +
                                                         loaderMainPageUrl +
                                                         "  <FONT color=#000000>This is not correct url!</p>"
                                                         );
                }
                window1.Owner = this;
                window1.Show();
            }
            //下面效果正确的前提 主窗体的 WindowStyle = System.Windows.WindowStyle.None; 
            private void MoveWindow1()
            {
                window1.Left = MainWindow1.Left + border1.Margin.Left;
                window1.Top = MainWindow1.Top + border1.Margin.Top;
                window1.Width = border1.Width;
                window1.Height = border1.Height;
            }
            private void imageMain1_MouseDown(object sender, MouseButtonEventArgs e)
            {
                DragMove();
            }
            private void MainWindow1_LocationChanged(object sender, EventArgs e)
            {
                MoveWindow1();
            }
            #endregion
            #region 九个图上按钮的单击事件...
            private void MinimizeButton_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
            {
                MainWindow1.WindowState = System.Windows.WindowState.Minimized;
            }
            private void XButton_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
            {
                DeleteNewEstIniFileName();
                Environment.Exit(0);
            }
            private void imageButton5_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
            {
                //官方网站
                PlayClickSound();
                UrlClass.Url.Nagivate(homePageUrl);
            }
            private void imageButton6_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
            {
                //官方论坛
                PlayClickSound();
                UrlClass.Url.Nagivate(bBsPageUrl);
            }
            private void imageButton7_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
            {
                //联系客服
                PlayClickSound();
                UrlClass.Url.Nagivate(serverPageUrl);
            }
            private void imageButton8_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
            {
                //系统设置
                PlayClickSound();
                //Window2 window2 = new Window2();
                //if (window2.ShowDialog() == true)
                //{
                //    MessageBox.Show("U pressed Ok Button!");
                //}
            }
            private void imageButton1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
            {
                //注册账号
                UrlClass.Url.Nagivate(registerPageUrl);
                PlayClickSound();
            }
            private void imageButton2_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
            {
                //密码修改
                UrlClass.Url.Nagivate(changePasswdUrl);
                PlayClickSound();
            }
            private void imageButton3_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
            {
                //手动升级
                if (startButton1.IsEnabled)
                {
                    PlayClickSound();
                    Microsoft.Win32.OpenFileDialog openFileDialog1 = new Microsoft.Win32.OpenFileDialog();
                    openFileDialog1.Filter = "完美世界补丁文件.7z|*.7z";
                    if (openFileDialog1.ShowDialog() == true)
                    {
                        
                        SevenZipExtract(openFileDialog1.FileName, AppDomain.CurrentDomain.BaseDirectory);
                        
                    }
                }
            }
            private void imageButton4_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
            {
                //关于程序
                PlayClickSound();
                AboutWindow about1 = new AboutWindow();
                about1.Owner = this;
                about1.ShowDialog();
            }
            private void StartButton_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
            {
                if (startButton1.IsEnabled)
                    PlayClickSound();
                label1.Content = "正在打开完美世界...";
                string elementDirectory = AppDomain.CurrentDomain.BaseDirectory + "\element";
                string elementExeFileName = AppDomain.CurrentDomain.BaseDirectory + "\element\elementclient.exe";
                System.IO.Directory.SetCurrentDirectory(elementDirectory);
                System.Diagnostics.ProcessStartInfo processStartInfo1 = new System.Diagnostics.ProcessStartInfo();
                processStartInfo1.FileName = elementExeFileName;
             
                if ( debugMode==true )
                    processStartInfo1.Arguments = " game:cpw console:1";//高度模式
                else
                    processStartInfo1.Arguments = " game:cpw";
                System.Diagnostics.Process.Start(processStartInfo1);
                
                
                Close();
            }
            private void PlayClickSound()
            {
                System.IO.Stream s = Properties.Resources.click;
                System.Media.SoundPlayer player = new System.Media.SoundPlayer(s);
                player.PlaySync();
            }
            #endregion
            private void CheckGameClientFileExists()
            {
                string elementDirectory = AppDomain.CurrentDomain.BaseDirectory + "\element";
                string elementExeFileName = AppDomain.CurrentDomain.BaseDirectory + "\element\elementclient.exe";
                if (!System.IO.Directory.Exists(elementDirectory))
                {
                    MessageBox.Show("请将本程序放在完美世界的目录下 然后再尝试!""提示"MessageBoxButton.OK, MessageBoxImage.Information);
                    Environment.Exit(0);
                }
                if (!System.IO.File.Exists(elementExeFileName))
                {
                    MessageBox.Show("elementclient.exe 文件不存在,程序坚决不执行!""提示"MessageBoxButton.OK, MessageBoxImage.Information);
                    Environment.Exit(0);
                }
            }
            private void MainWindow1_Initialized(object sender, EventArgs e)
            {
                CheckPatcherIniFileExists();
                CheckGameClientFileExists(); 
                Check7zSevenZipSharpDllExists();
                border1.Visibility = System.Windows.Visibility.Hidden;
                image1.Width = 0;
                label1.Content = "连接服务器...";
                label2.Content = "";
                label3.Content = "";
                startButton1.IsEnabled = false;
                imageButton3.IsEnabled = false;
                //更新文件所存在的临时目录
                CreateUpdateTmpFolder();
                //读取配置信息
                ReadConfig();
                GetNewestVersionNumber();
                
                label3.Content = "游戏发布序号:" + updateVersionNumber;
            }
            #region 7za 解压文件...
            //private string fileName = @"D:AdministratorwwwrootCPWwmgjUpdate.7z";
            //private string directory = @"D:AdministratorDesktop完美世界国际版";
            private string dll7z = AppDomain.CurrentDomain.BaseDirectory + "7z.dll";
            private string dllSevenZipSharp = AppDomain.CurrentDomain.BaseDirectory + "SevenZipSharp.dll";
            private int MaxValue = 0;
            private int CurrentValue = 0;
            /// <summary>
            /// 图片进度条
            /// </summary>
            /// <param name="current"></param>
            /// <param name="max"></param>
            /// <param name="imageWidth">图片的实际宽度</param>
            /// <param name="image1"></param>
            private static void ImageProgressBar(double current, double max, double imageWidth, System.Windows.Controls.Image image1)
            {
                if (max != 0)
                    image1.Width = System.Math.Round((current / max) * imageWidth);
            }
            private void SevenZipExtract(string fileName, string directory)
            {
                if (System.IO.File.Exists(fileName) && System.IO.Directory.Exists(directory))
                {
                    SevenZipExtractor.SetLibraryPath(dll7z);
                    label1.Content = "开始更新文件";
                    var extractor = new SevenZipExtractor(fileName);
                   
                    MaxValue = extractor.ArchiveFileData.Count;
                    extractor.FileExtractionStarted += new EventHandler<FileInfoEventArgs>(extr_FileExtractionStarted);
                    extractor.BeginExtractArchive(directory);
                }
            }
            void extr_FileExtractionStarted(object sender, FileInfoEventArgs e)
            {
                label1.Content = String.Format("更新 {0}", e.FileInfo.FileName);
                label2.Content = "";
                imageButton3.IsEnabled = false;
                startButton1.IsEnabled = false;
                CurrentValue += 1;
                ImageProgressBar(CurrentValue, MaxValue, 193, image1);
                if (CurrentValue >= MaxValue)
                {
                    //复制最新INI替换本地的INI
                    System.IO.File.Copy(newestIniFileName, IniFileName, true);
                    
                    label1.Content = "游戏更新完成";
                    label2.Content = "";
                    label3.Content = "游戏发布序号:" + updateVersionNumber;
                    startButton1.IsEnabled = true;
                    imageButton3.IsEnabled = true;
                    imageButton3.IsEnabled = true;
                    if (System.IO.File.Exists(updateFileName))
                         System.IO.File.Delete(updateFileName);
                }
            }
            private void Check7zSevenZipSharpDllExists()
            {
                bool b1 = System.IO.File.Exists(dll7z);
                bool b2 = System.IO.File.Exists(dllSevenZipSharp);
                if (!b1)
                {
                    MessageBox.Show("7z.dll 不存在!""错误"MessageBoxButton.OK, MessageBoxImage.Error);
                    Close();
                }
                if (!b2)
                {
                    MessageBox.Show("SevenZipSharp.dll 不存在!""错误"MessageBoxButton.OK, MessageBoxImage.Error);
                    Close();
                }
            }
            #endregion
            private void MainWindow1_Loaded(object sender, RoutedEventArgs e)
            {
               // MessageBox.Show(Environment.Version.Revision.ToString());
                InitialWindow1();
                MoveWindow1();
                WpfApplication.DispatcherHelper.DoEvents();
                System.Threading.Thread.Sleep(1500);
                if (System.IO.File.Exists(IniFileName))
                {
                    ////下载patcher.ini
                    if (WpfApplication.HttpClass.UrlIsExists(VersionCheckUrl))
                    {
                        bool b = WpfApplication.HttpClass.DownloadFile(VersionCheckUrl, newestIniFileName, label1, image1, 193);
                        if (b)
                        {
                            //  System.Threading.Thread.Sleep(1500);
                            label1.Content = "正在检查客户端版本";
                            //System.Threading.Thread.Sleep(1500);
                            //读取配置信息
                            ReadConfig();
                            GetNewestVersionNumber();
                            //比较最新版本信息和当前的版本信息
                            if (newestVersionNumber > updateVersionNumber)
                            {
                                label1.Content = "客户端已有新的版本";
                                label2.Content = "准备进行更新";
                                PlayClickSound();
                                UpdateWindow1 updateWindow1 = new UpdateWindow1();
                                updateWindow1.label2.Content = "目前版本:  " + updateVersionNumber.ToString();
                                updateWindow1.label3.Content = "最新版本:  " + newestVersionNumber.ToString();
                                updateWindow1.textBlock1.Text = "备注: " + updateTips;
                                if (updateWindow1.ShowDialog() == true)
                                {
                                    //下载客户端补丁文件
                                    if (WpfApplication.HttpClass.UrlIsExists(ClientUpdateDatakUrl))
                                    {
                                        System.Threading.Thread.Sleep(500);
                                        label1.Content = "准备下载文件";
                                        label2.Content = "";
                                        bool b1 = WpfApplication.HttpClass.DownloadFile(ClientUpdateDatakUrl, updateFileName, label1, image1, 193);
                                        if (b1)
                                        {
                                            System.Threading.Thread.Sleep(500);
                                            label1.Content = "准备更新客户端文件";
                                            SevenZipExtract(updateFileName, AppDomain.CurrentDomain.BaseDirectory);
                                        }
                                    }
                                    else
                                    {
                                        label1.Content = "补丁文件下载失败";
                                        label2.Content = "";
                                        startButton1.IsEnabled = true;
                                        imageButton3.IsEnabled = true;
                                    }
                                }
                                else
                                {
                                    label1.Content = "游戏更新已被取消";
                                    label2.Content = "";
                                    startButton1.IsEnabled = true;
                                    imageButton3.IsEnabled = true;
                                }
                            }
                            else
                            {
                                label1.Content = "游戏更新完成";
                                label2.Content = "";
                                label3.Content = "游戏发布序号:" + newestVersionNumber;
                                startButton1.IsEnabled = true;
                                imageButton3.IsEnabled = true;
                            }
                        }
                    }
                    else
                    {
                        label1.Content = "更新服务器连接失败";
                        label2.Content = "请尝试其他更新服务";
                        startButton1.IsEnabled = true;
                        imageButton3.IsEnabled = true;
                    }
                }
                else
                {
                    label1.Content = "更新服务器连接失败";
                    label2.Content = "请尝试其他更新服务";
                    startButton1.IsEnabled = true;
                    imageButton3.IsEnabled = true;
                }
            }
            private void DeleteNewEstIniFileName()
            {
                if (System.IO.File.Exists(newestIniFileName))
                    System.IO.File.Delete(newestIniFileName);
            }
            private void MainWindow1_Closed(object sender, EventArgs e)
            {
                window1.Close();
                DeleteNewEstIniFileName();
            } 
        }
    }
     

    DispatcherHelper.cs
    using System;
    using System.Windows.Threading;
    using System.Security.Permissions;
    //  立即退出程序 Environment.Exit(0);
    namespace WpfApplication
    {
        public static class DispatcherHelper
        {
            [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
            public static void DoEvents()
            {
                DispatcherFrame frame = new DispatcherFrame();
                Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(ExitFrames), frame);
                try 
                { 
                    Dispatcher.PushFrame(frame); 
                }
                catch (InvalidOperationException
                {
                }
            }
            private static object ExitFrames(object frame)
            {
                ((DispatcherFrame)frame).Continue = false;
                return null;
            }
        }
    }

    IniFilesClass.cs
     
            #region 示例...
    //         private void button1_Click(object sender, EventArgs e)
    //         {
    //             IniFile ini = new IniFile(IniFile.AppIniName);
    //             ini.WriteString("Settings", "Name", textBox1.Text);
    //         }
    // 
    //         private void button2_Click(object sender, EventArgs e)
    //         {
    //             IniFile ini = new IniFile(IniFile.AppIniName);
    //             textBox1.Text = ini.ReadString("Settings", "Name", "没有文字");
    //         }
    // 
    // 
    // 
    // 
    //         //Integer
    //         private void button3_Click(object sender, EventArgs e)
    //         {
    //             IniFile ini = new IniFile(IniFile.AppIniName);
    //             ini.WriteInteger("Settings", "Age", 26);
    //         }
    // 
    //         private void button4_Click(object sender, EventArgs e)
    //         {
    //             IniFile ini = new IniFile(IniFile.AppIniName);
    //             int nAge = ini.ReadInteger("Settings", "Age", 0);
    //             textBox1.Text = nAge.ToString();
    //         }
    // 
    //         //bool
    //         private void button5_Click(object sender, EventArgs e)
    //         {
    //             IniFile ini = new IniFile(IniFile.AppIniName);
    //             ini.WriteBool("Settings", "Man", checkBox1.Checked);
    //         }
    // 
    //         private void button6_Click(object sender, EventArgs e)
    //         {
    //             IniFile ini = new IniFile(IniFile.AppIniName);
    //             checkBox1.Checked = ini.ReadBool("Settings", "Man", true);
    //         }
            #endregion
    using System;
    using System.IO;
    using System.Runtime.InteropServices;
    using System.Text;
    namespace IniFilesClass
    {
        public class IniFile
        {    
            public IniFile(string INIPath)
            {
                iniFileName = INIPath;
            }
             /*
             * [配置]
             * name = roman
             * age = 26
             * man = true;
             */
            private static string iniFileName;
            public static string AppFileName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName; 
            /// <summary>
            /// 和程序名子一样的  C:WindowsFormsApplication1.ini
            /// </summary>
            public static string AppIniName = AppDomain.CurrentDomain.BaseDirectory + System.IO.Path.GetFileNameWithoutExtension(AppFileName) + ".ini";
            
            /// <summary>
            /// 和程序名子一样的   C:WindowsFormsApplication1.exe.ini
            /// </summary>
            public static string AppIniName1 = AppFileName + ".ini";
            #region DllImport...
            [DllImport("kernel32")]
            private static extern long WritePrivateProfileString(string SectionName, string KeyName, string Value, string FileName);
            [DllImport("kernel32")]
            private static extern int GetPrivateProfileString(string SectionName, string KeyName, string sDefault, StringBuilder retVal, int size, string FileName);
            [DllImport("kernel32")]
            private static extern int GetPrivateProfileInt(string SectionName, string KeyName, int nDefault, string FileName); 
            #endregion
            public void WriteString(string Section, string Key, string Value)
            {
                WritePrivateProfileString(Section, Key, Value,iniFileName);
            }
       
            public string ReadString(string Section, string Key, string sDefault)
            {
                StringBuilder sb = new StringBuilder(255);
                int i = GetPrivateProfileString(Section, Key, sDefault, sb, 255, iniFileName);
                return sb.ToString();
            }
            public void WriteInteger(string Section, string Key, int nValue)
            {
                WritePrivateProfileString(Section,Key,nValue.ToString(),iniFileName);
            }
      
            public int ReadInteger(string Section, string Key, int nDefault)
            {
                return  GetPrivateProfileInt(Section, Key, nDefault, iniFileName);
            }
            public void WriteBool(string Section, string Key, bool bValue)
            {
                WritePrivateProfileString(Section, Key, bValue.ToString(), iniFileName);
            }
         
            public bool ReadBool(string Section, string Key, bool nDefault)
            {
                string Value = ReadString(Section,Key,"");
                Value=Value.ToUpper();
                switch ( Value )
                {
                    case "TRUE":
                        return true;
                       
                    case "FALSE":
                        return false;
                        
                    default:
                        return false;
                }
            }
        
        
        }
    }

    UrlClass.cs
    using System;
    using System.Collections.Generic;
    using System.Text.RegularExpressions;
    namespace UrlClass
    {
     
        public class Url
        {
            /// <summary>
            /// 检测串值是否为合法的网址格式
            /// </summary>
            /// <param name="strValue">要检测的String值</param>
            /// <returns>成功返回true 失败返回false</returns>
            public static bool IsUrlFormat(string strValue)
            {
                return CheckIsFormat(@"(http://)?([w-]+.)+[w-]+(/[w- ./?%&=]*)?", strValue);
            }
            /// <summary>
            /// 检测串值是否为合法的格式
            /// </summary>
            /// <param name="strRegex">正则表达式</param>
            /// <param name="strValue">要检测的String值</param>
            /// <returns>成功返回true 失败返回false</returns>
            public static bool CheckIsFormat(string strRegex, string strValue)
            {
                if (strValue != null && strValue.Trim() != "")
                {
                    Regex re = new Regex(strRegex);
                    if (re.IsMatch(strValue))
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                return false;
            }
        
            /// <summary>
            /// 浏览网页地址
            /// </summary>
            /// <param name="url"></param>
            /// <returns></returns>
            public static bool Nagivate(string url)
            {
                bool IsUrl = IsUrlFormat(url);
                if (IsUrl)
                {
                    System.Diagnostics.Process.Start(url);
                }
                return IsUrl;
            }
            /// <summary>
            /// 判断一个Url是否能连接成功
            /// </summary>
            /// <param name="url"></param>
            /// <returns></returns>
            public static bool CanConnect(string url)
            {
                return true;
            }
        }
    }
     

    HttpClass.cs
    using System;
    //using System.Collections.Generic;
    //using System.Text;
    //using System.Net;
    //using System.IO;
    namespace WpfApplication
    {
        public class HttpClass
        {
            [System.Runtime.InteropServices.DllImport("wininet")]
            private extern static bool InternetGetConnectedState(out int connectionDescription, int reservedValue);
            //判断网络是连接到互联网
            public static bool IsNetWorkConnect()
            {
                int i = 0;
                return InternetGetConnectedState(out i, 0) ? true : false;
            }
            //转换BYTE为 MB 格式
            private static string BytesToString(decimal Bytes)
            {
                decimal Kb = System.Math.Round(Bytes / 1024);
                if (Kb > 1000)
                    return string.Format("{0:0.0} MB", Kb / 1024);
                else
                    return string.Format("{0:0} KB", Kb);
            }
            //下载网络文件
            /// <summary>
            /// 下载网络文件 带进度条
            /// </summary>
            /// <param name="URL"></param>
            /// <param name="fileName"></param>
            /// <param name="progressBar1"></param>
            /// <returns></returns>
            public static bool DownloadFile(string URL, string fileName, System.Windows.Controls.ProgressBar progressBar1)
            {
                try
                {
                    System.Net.HttpWebRequest httpWebRequest1 = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                    System.Net.HttpWebResponse httpWebResponse1 = (System.Net.HttpWebResponse)httpWebRequest1.GetResponse();
                    long totalLength = httpWebResponse1.ContentLength;
                    progressBar1.Maximum = (int)totalLength;
                    System.IO.Stream stream1 = httpWebResponse1.GetResponseStream();
                    System.IO.Stream stream2 = new System.IO.FileStream(fileName, System.IO.FileMode.Create);
                    long currentLength = 0;
                    byte[] by = new byte[1024];
                    int osize = stream1.Read(by, 0, (int)by.Length);
                    while (osize > 0)
                    {
                        WpfApplication.DispatcherHelper.DoEvents();
                        currentLength = osize + currentLength;
                        stream2.Write(by, 0, osize);
                        progressBar1.Value = (int)currentLength;
                        osize = stream1.Read(by, 0, (int)by.Length);
                    }
                    stream2.Close();
                    stream1.Close();
                    return (currentLength == totalLength);
                }
                catch
                {
                    return false;
                }
            }
            /// <summary>
            /// 下载网络文件 带进度条 显示当前值和 最大值 100KB / 50mb
            /// </summary>
            /// <param name="URL"></param>
            /// <param name="fileName"></param>
            /// <param name="progressBar1"></param>
            /// <param name="label1"></param>
            /// <returns></returns>
            public static bool DownloadFile(string URL, string fileName, System.Windows.Controls.ProgressBar progressBar1, System.Windows.Controls.Label label1)
            {
                try
                {
                    System.Net.HttpWebRequest httpWebRequest1 = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                    System.Net.HttpWebResponse httpWebResponse1 = (System.Net.HttpWebResponse)httpWebRequest1.GetResponse();
                    long totalLength = httpWebResponse1.ContentLength;
                    progressBar1.Maximum = (int)totalLength;
                    System.IO.Stream stream1 = httpWebResponse1.GetResponseStream();
                    System.IO.Stream stream2 = new System.IO.FileStream(fileName, System.IO.FileMode.Create);
                    long currentLength = 0;
                    byte[] by = new byte[1024];
                    int osize = stream1.Read(by, 0, (int)by.Length);
                    while (osize > 0)
                    {
                        WpfApplication.DispatcherHelper.DoEvents();
                        currentLength = osize + currentLength;
                        stream2.Write(by, 0, osize);
                        progressBar1.Value = (int)currentLength;
                        label1.Content = String.Format("{0} / {1}", BytesToString(currentLength), BytesToString(totalLength));
                        osize = stream1.Read(by, 0, (int)by.Length);
                    }
                    stream2.Close();
                    stream1.Close();
                    return (currentLength == totalLength);
                }
                catch
                {
                    return false;
                }
            }
            /// <summary>
            /// 下载网络文件 提供一个
            /// </summary>
            /// <param name="URL"></param>
            /// <param name="fileName"></param>
            /// <param name="label1">LABEL控件</param>
            /// <param name="image1">图片控件 </param>
            /// <param name="image1Width">图片的宽度</param>
            /// <returns></returns>
            public static bool DownloadFile(string URL,
                                            string fileName,
                                            System.Windows.Controls.Label label1,
                                            System.Windows.Controls.Image image1,
                                            double image1Width
                                            )
            {
                try
                {
                    System.Net.HttpWebRequest httpWebRequest1 = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                    System.Net.HttpWebResponse httpWebResponse1 = (System.Net.HttpWebResponse)httpWebRequest1.GetResponse();
                    long totalLength = httpWebResponse1.ContentLength;
                    System.IO.Stream stream1 = httpWebResponse1.GetResponseStream();
                    System.IO.Stream stream2 = new System.IO.FileStream(fileName, System.IO.FileMode.Create);
                    long currentLength = 0;
                    byte[] by = new byte[1024];
                    int osize = stream1.Read(by, 0, (int)by.Length);
                    while (osize > 0)
                    {
                        WpfApplication.DispatcherHelper.DoEvents();
                        currentLength = osize + currentLength;
                        stream2.Write(by, 0, osize);
                        ImageProgressBar(currentLength, totalLength, image1Width, image1);
                        label1.Content = String.Format("{0} / {1}", BytesToString(currentLength), BytesToString(totalLength));
                        osize = stream1.Read(by, 0, (int)by.Length);
                    }
                    stream2.Close();
                    stream1.Close();
                    return (currentLength == totalLength);
                }
                catch
                {
                    return false;
                }
            }
            //URL 是否能连接
            /// <summary>
            /// 判断网络文件是否存在 1.5秒得到出结果 如这样的格式  http://191.168.1.105:8000/CPW/wmgjUpdate.7
            /// </summary>
            /// <param name="URL"></param>
            /// <returns></returns>
            public static bool UrlIsExists(string URL)
            {
                try
                {
                    System.Net.WebRequest webRequest1 = System.Net.WebRequest.Create(URL);
                    webRequest1.Timeout = 2500;
                    System.Net.WebResponse webResponse1 = webRequest1.GetResponse();
                    return (webResponse1 == null ? false : true);
                }
                catch
                {
                    return false;
                }
            }
            /// <summary>
            /// 图片进度条
            /// </summary>
            /// <param name="current"></param>
            /// <param name="max"></param>
            /// <param name="imageWidth">图片的实际宽度</param>
            /// <param name="image1"></param>
            public static void ImageProgressBar(double current, double max, double imageWidth, System.Windows.Controls.Image image1)
            {
                if (max != 0)
                    image1.Width = System.Math.Round((current / max) * imageWidth);
            }
        }
    }
     

    ImageButton.xaml
    <UserControl x:Class="WpfApplication1.ImageButton"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
                 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
                 mc:Ignorable="d" Height="28.654" Width="83.385">
        <Grid>
            <Image x:Name="image1" HorizontalAlignment="Left" Height="29" VerticalAlignment="Top" Width="84" Margin="-0.125,0,0,0" Source="Images/button-bg.png" Stretch="UniformToFill" MouseLeave="image1_MouseLeave" MouseMove="image1_MouseMove" MouseUp="image1_MouseUp" MouseLeftButtonUp="image1_MouseLeftButtonUp" MouseLeftButtonDown="image1_MouseLeftButtonDown"/>
            <Label x:Name="label1" Content="按钮1"  FontFamily="FangSong" Height="29"  HorizontalContentAlignment="Center" Margin="-0.125,0,0,0" VerticalAlignment="Top" Width="84" MouseLeave="image1_MouseLeave" MouseMove="image1_MouseMove" MouseUp="image1_MouseUp" MouseLeftButtonUp="image1_MouseLeftButtonUp" MouseLeftButtonDown="image1_MouseLeftButtonDown" HorizontalAlignment="Left" FontSize="14">
                <Label.Foreground>
                    <SolidColorBrush Color="#FFB3D0E9"/>
                </Label.Foreground>
            </Label>
        </Grid>
    </UserControl>
     

    ImageButton.xaml.cs
     
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    using System.ComponentModel;
    using System.IO;
    namespace WpfApplication1
    {
        /// <summary>
        /// ImageButton.xaml 的交互逻辑
        /// </summary>
        public partial class ImageButton : UserControl
        {
            public ImageButton()
            {
                InitializeComponent();
            }
            //属性
            //button-bg.png
            //button-clicked.png
            //button-hover.png
            //button-disabled.png
            //TEXT
            //Enabled
            //Clicked event
            //Hint
            //public string BaseImage;
            //public string LeftMouseDownImage;
            //public string MouseMoveImage;
            //public string MouseLeaveImage;
            //public string DisabledImage;
            #region TEXT
            [Category("Common Properties")]
            [Description("获取或设置文本")]
            public string Text
            {
                get
                {
                    return (string)label1.Content;
                }
                set
                {
                    label1.Content = value;
                }
            }
            #endregion
            #region BaseSource
            [Category("Common Properties")]
            [Description("获取或设置默认的按钮显示的图片")]
            public ImageSource BaseSource
            {
                get
                {
                    return null;
                }
                set
                {
                    //  image1.Source = value;
                    image1.Source = value;// new BitmapImage(new Uri(BaseImage, UriKind.Relative));
                }
            }
            #endregion
            #region Disabled
            [Category("Common Properties")]
            [Description("获取或设置是否可以使用")]
            public bool IsEnabled
            {
                get
                {
                    return image1.IsEnabled;
                }
                set
                {
                    if (value == true)
                    {
                        
                        image1.Source = new BitmapImage(new Uri("Images/button-bg.png"UriKind.Relative));
                        label1.Foreground = new SolidColorBrush(Color.FromArgb(255, 179, 208, 233));
                        label1.IsEnabled = true;
                        image1.IsEnabled = true;
                    }
                    if (value == false)
                    {
                        image1.Source = new BitmapImage(new Uri("Images/button-disabled.png"UriKind.Relative));
                        label1.Foreground = new SolidColorBrush(Color.FromArgb(100, 76, 76, 76));
                        label1.IsEnabled = false;
                        image1.IsEnabled = false;
                    }
                }
            }
            #endregion
            private void SetImageSource(string fileName)
            {
                if (File.Exists(fileName))
                    image1.Source = new BitmapImage(new Uri(fileName, UriKind.Relative));
            }
            private void image1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
            {
                image1.Source = new BitmapImage(new Uri("Images/button-clicked.png"UriKind.RelativeOrAbsolute));
            }
            private void image1_MouseLeave(object sender, MouseEventArgs e)
            {
                image1.Source = new BitmapImage(new Uri("Images/button-bg.png"UriKind.Relative));
            }
            private void image1_MouseMove(object sender, MouseEventArgs e)
            {
                image1.Source = new BitmapImage(new Uri("Images/button-hover.png"UriKind.Relative));
            }
            private void image1_MouseUp(object sender, MouseButtonEventArgs e)
            {
                image1.Source = new BitmapImage(new Uri("Images/button-bg.png"UriKind.Relative));
            }
            
            private void image1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
            {
                //clickEvent
            }
        }
    }
  • 相关阅读:
    移动端文本编辑器
    jquery移动端日期插件
    Spring 4集成 Quartz2(转)
    json 特殊字符 javascript 特殊字符处理(转载)
    解决使用JavaScriptConvert转换对象为Json时,中文和&符号被转码的问题
    RFID的winform程序心得2
    异步编程模型
    DataGridView获取或者设置当前单元格的内容
    DataGridView修改数据并传到数据库
    把存储过程结果集SELECT INTO到临时表
  • 原文地址:https://www.cnblogs.com/xe2011/p/3762752.html
Copyright © 2011-2022 走看看