原版是从网上找了一位大神的,自己只是用了一点适合自己的。 具体实现 1.首先已经确认WPF中没有实现最小化托盘的类与方法,用到了winform中的程序集 using Drawing = System.Drawing; using Forms = System.Windows.Forms; 2.XAML的后代相应事件的Demo,只是为了看起来方便~!其中也包含了在任务栏中不现实图标,只在托盘中显示。双击实现窗口的还原。没用到大神写的,自己琢磨了个,令人想不到的蛋疼的后果还没出现,也就暂时这样了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
namespace 最小化到托盘 { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { //妈蛋找了你一天,,启动后不现实任务栏图标!!!!!!!!!!!!!!!!!!!! this.ShowInTaskbar = false; InitializeComponent(); } /// <summary> /// 托盘右击菜单--上线按钮 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MenuItem_OnlineClick(object sender, EventArgs e) { MessageBox.Show("提示上线!"); } /// <summary> /// 托盘右击菜单--离开按钮 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MenuItem_LeaveClick(object sender, EventArgs e) { MessageBox.Show("提示暂时离开!"); } /// <summary> /// 托盘右击菜单--在忙按钮 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MenuItem_BusyClick(object sender, EventArgs e) { MessageBox.Show("提示在忙!"); } /// <summary> /// 托盘右击菜单--请勿打扰按钮 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MenuItem_NoBotherClick(object sender, EventArgs e) { MessageBox.Show("提示请勿打扰!"); } /// <summary> /// 托盘右击菜单--隐身按钮 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MenuItem_HideClick(object sender, EventArgs e) { MessageBox.Show("提示隐身!"); } /// <summary> /// 托盘右击菜单--离线按钮 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MenuItem_OffLineClick(object sender, EventArgs e) { MessageBox.Show("提示离线!"); } /// <summary> /// 托盘右击菜单--关于我们按钮 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MenuItem_AboutUsClick(object sender, EventArgs e) { MessageBox.Show("提示关于我们!"); } /// <summary> /// 托盘小图标的双击事件--最小化的状态下双击还原 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void NotificationAreaIcon_MouseDoubleClick_1(object sender, MouseButtonEventArgs e) { //if (e.ChangedButton==MouseButton.Left) //{ if (this.WindowState == WindowState.Minimized) { WindowState = WindowState.Normal; } // } } private void MenuItem_ExitClick(object sender, EventArgs e) { this.Close(); } private void Window_MouseMove_1(object sender, MouseEventArgs e) { } //以下代码想实现即时聊天的记住密码功能,度娘说要存入配置文件,没搞成功,希望看到的人帮我这个忙~ private void Button_Click_1(object sender, RoutedEventArgs e) { //点击按钮往配置文件存入信息 Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); cfa.AppSettings.Settings["LogName"].Value = "123"; cfa.Save(); MessageBox.Show(ConfigurationManager.AppSettings["LogName"]); } } } |
3.最主要的是大神写的这个类,学习编程五个月,能看懂的不是太多,稍微明白点意思,但是说不上来,直接贴代码吧。以后在研究!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 |
using System; using System.Collections.Generic; using System.ComponentModel; using System.Windows; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Threading; using Drawing = System.Drawing; using Forms = System.Windows.Forms; namespace 最小化到托盘 { /// <summary> /// Represents a thin wrapper for <see cref="Forms.NotifyIcon"/> /// </summary> [ContentProperty("Text")] [DefaultEvent("MouseDoubleClick")] public class NotificationAreaIcon : FrameworkElement { Forms.NotifyIcon notifyIcon; public static readonly RoutedEvent MouseClickEvent = EventManager.RegisterRoutedEvent( "MouseClick", RoutingStrategy.Bubble, typeof(MouseButtonEventHandler), typeof(NotificationAreaIcon)); public static readonly RoutedEvent MouseDoubleClickEvent = EventManager.RegisterRoutedEvent( "MouseDoubleClick", RoutingStrategy.Bubble, typeof(MouseButtonEventHandler), typeof(NotificationAreaIcon)); public static readonly DependencyProperty IconProperty = DependencyProperty.Register("Icon", typeof(ImageSource), typeof(NotificationAreaIcon)); public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(NotificationAreaIcon)); public static readonly DependencyProperty FormsContextMenuProperty = DependencyProperty.Register("MenuItems", typeof(List<Forms.MenuItem>), typeof(NotificationAreaIcon), new PropertyMetadata(new List<Forms.MenuItem>())); protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); // Create and initialize the window forms notify icon based notifyIcon = new Forms.NotifyIcon(); notifyIcon.Text = Text; if (!DesignerProperties.GetIsInDesignMode(this)) { notifyIcon.Icon = FromImageSource(Icon); } notifyIcon.Visible = FromVisibility(Visibility); if (this.MenuItems != null && this.MenuItems.Count > 0) { notifyIcon.ContextMenu = new System.Windows.Forms.ContextMenu(this.MenuItems.ToArray()); } notifyIcon.MouseDown += OnMouseDown; notifyIcon.MouseUp += OnMouseUp; notifyIcon.MouseClick += OnMouseClick; notifyIcon.MouseDoubleClick += OnMouseDoubleClick; Dispatcher.ShutdownStarted += OnDispatcherShutdownStarted; } private void OnDispatcherShutdownStarted(object sender, EventArgs e) { notifyIcon.Dispose(); } private void OnMouseDown(object sender, Forms.MouseEventArgs e) { OnRaiseEvent(MouseDownEvent, new MouseButtonEventArgs( InputManager.Current.PrimaryMouseDevice, 0, ToMouseButton(e.Button))); } private void OnMouseUp(object sender, Forms.MouseEventArgs e) { OnRaiseEvent(MouseUpEvent, new MouseButtonEventArgs( InputManager.Current.PrimaryMouseDevice, 0, ToMouseButton(e.Button))); } private void OnMouseDoubleClick(object sender, Forms.MouseEventArgs e) { OnRaiseEvent(MouseDoubleClickEvent, new MouseButtonEventArgs( InputManager.Current.PrimaryMouseDevice, 0, ToMouseButton(e.Button))); } private void OnMouseClick(object sender, Forms.MouseEventArgs e) { OnRaiseEvent(MouseClickEvent, new MouseButtonEventArgs( InputManager.Current.PrimaryMouseDevice, 0, ToMouseButton(e.Button))); } private void OnRaiseEvent(RoutedEvent handler, MouseButtonEventArgs e) { e.RoutedEvent = handler; RaiseEvent(e); } public List<Forms.MenuItem> MenuItems { get { return (List<Forms.MenuItem>)GetValue(FormsContextMenuProperty); } set { SetValue(FormsContextMenuProperty, value); } } public ImageSource Icon { get { return (ImageSource)GetValue(IconProperty); } set { SetValue(IconProperty, value); } } public string Text { get { return (string)GetValue(TextProperty); } set { SetValue(TextProperty, value); } } public event MouseButtonEventHandler MouseClick { add { AddHandler(MouseClickEvent, value); } remove { RemoveHandler(MouseClickEvent, value); } } public event MouseButtonEventHandler MouseDoubleClick { add { AddHandler(MouseDoubleClickEvent, value); } remove { RemoveHandler(MouseDoubleClickEvent, value); } } #region Conversion members private static Drawing.Icon FromImageSource(ImageSource icon) { if (icon == null) { return null; } Uri iconUri = new Uri(icon.ToString()); return new Drawing.Icon(Application.GetResourceStream(iconUri).Stream); } private static bool FromVisibility(Visibility visibility) { return visibility == Visibility.Visible; } private MouseButton ToMouseButton(Forms.MouseButtons button) { switch (button) { case Forms.MouseButtons.Left: return MouseButton.Left; case Forms.MouseButtons.Right: return MouseButton.Right; case Forms.MouseButtons.Middle: return MouseButton.Middle; case Forms.MouseButtons.XButton1: return MouseButton.XButton1; case Forms.MouseButtons.XButton2: return MouseButton.XButton2; } throw new InvalidOperationException(); } #endregion Conversion members } } |
from:https://www.cnblogs.com/gchlcc/p/4987042.html
View DetailsWPF程序也可以很轻松的实现类似QQ那样最小化到任务栏的功能。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
WindowState ws; WindowState wsl; NotifyIcon notifyIcon; #region Constructions public MainWindow()();//显示托盘。 icon(); //保证窗体显示在上方。 wsl = WindowState; } #endregion private void icon() { this.notifyIcon = new NotifyIcon(); this.notifyIcon.BalloonTipText = "Hello, 文件监视器"; //设置程序启动时显示的文本 this.notifyIcon.Text = "文件监视器";//最小化到托盘时,鼠标点击时显示的文本 this.notifyIcon.Icon = new System.Drawing.Icon("Downloads.ico");//程序图标 this.notifyIcon.Visible = true; notifyIcon.MouseDoubleClick += OnNotifyIconDoubleClick; this.notifyIcon.ShowBalloonTip(1000); } private void OnNotifyIconDoubleClick(object sender, EventArgs e) { this.Show(); WindowState = wsl; } private void Window_StateChanged(object sender, EventArgs e) { ws = WindowState; if (ws == WindowState.Minimized) { this.Hide(); } } |
from:https://www.cnblogs.com/Gyoung/archive/2012/12/06/2805932.html
View Details让WPF应用最小到系统托盘?可以调用System.Windows.Forms.NotifyIcon来实现,下面是示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
public partial class MainWindow : Window { private NotifyIcon notifyIcon; public MainWindow() { InitializeComponent(); this.notifyIcon = new NotifyIcon(); this.notifyIcon.BalloonTipText = "系统监控中... ..."; this.notifyIcon.ShowBalloonTip(2000); this.notifyIcon.Text = "系统监控中... ..."; this.notifyIcon.Icon = new System.Drawing.Icon(@"AppIcon.ico"); this.notifyIcon.Visible = true; //打开菜单项 System.Windows.Forms.MenuItem open = new System.Windows.Forms.MenuItem("Open"); open.Click += new EventHandler(Show); //退出菜单项 System.Windows.Forms.MenuItem exit = new System.Windows.Forms.MenuItem("Exit"); exit.Click += new EventHandler(Close); //关联托盘控件 System.Windows.Forms.MenuItem[] childen = new System.Windows.Forms.MenuItem[] { open, exit }; notifyIcon.ContextMenu = new System.Windows.Forms.ContextMenu(childen); this.notifyIcon.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler((o, e) => { if (e.Button == MouseButtons.Left) this.Show(o, e); }); } private void Show(object sender, EventArgs e) { this.Visibility = System.Windows.Visibility.Visible; this.ShowInTaskbar = true; this.Activate(); } private void Hide(object sender, EventArgs e) { this.ShowInTaskbar = false; this.Visibility = System.Windows.Visibility.Hidden; } private void Close(object sender, EventArgs e) { System.Windows.Application.Current.Shutdown(); } } |
运行时发现,程序一定要能找到ICON,否则会报错,并且ICON还没包含到程序中,需要一个额外的ICON来做托盘图标。当然这个都是能解决的:
1 |
this.notifyIcon.Icon = new System.Drawing.Icon(@"AppIcon.ico"); |
将以上一句替换成下面内容,意思就是读取程序图标,来作为托盘图标
1 |
this.notifyIcon.Icon = System.Drawing.Icon.ExtractAssociatedIcon(System.Windows.Forms.Application.ExecutablePath); |
运行,搞定,这样你的程序就不用拖着一个ICON文件当累赘了。 from:https://www.cnblogs.com/ke10/archive/2012/11/16/NotifyIcon.html
View Details就本人而言,C#中关闭应用主要有以下途径: 1.Close():关闭当前窗口,可以在OnClosing和 OnClosed中捕获消息,在OnClosing的时候,可以取消关闭窗口 2.Application.Current.Shutdown()/App.Current.Shutdown(): 关闭当前程序,如果有其他线程没有结束,不会关闭 3.Environment.Exit(0):强制退出,即使有其他的线程没有结束 4.Process类的CloseMainWindow, Kill:Process.CloseMainWindow是GUI程序的最友好结束方式,从名字上就可以看出来它是通过结束主窗体,相当于用户点击窗体的关闭按钮或者按Alt + F4 5.Environment类的FailFast:这是最暴力最彻底最直接的方法,一般不建议使用 现对各方式做简单的介绍: Close():如过调用了Close,而在Closing中没有显示的取消退出,则系统可以退出,这种情况仅仅是在没有多余线程,没有其他窗口启动的时候,如果有其他窗口同时启动,则要考虑App.Current.ShutdownMode。 Application.Current.Shutdown()/App.Current.Shutdown():其使用讲究最多。 在WPF应用程序的关闭是有ShutdownMode属性设置,具有3中枚举类型的值: 1)OnLastWindowClose(默认值)—应用程序最后一个窗体关闭时关闭应用程序 2)OnMainWindowClose—应用程序主窗体关闭时关闭应用程序 3)OnExplicitShutdown—显示调用关闭 示例如下: <Application x:Class="TestApplication.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation%22 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml%22 StartupUri="Window1.xaml" ShutdownMode="OnMainWindowClose"> </Application> Environment.Exit(0):Environment.Exit相当于在Main函数中的return指令。不过它不会执行代码块的finally块(如果有的话),但资源清理还是要进行的。它是最常见的退出当前进程的方法之一。在Main函数中我们可以直接return语句便退出了程序。如果不在Main函数内,那么Environment.Exit方法就可以派上用场。 示例如下: private void CloseApp() { CloseSignal(); AppManager.Instance.Close(); Environment.Exit(0); } Environment类的FailFast:此方法更速度,它甚至不需要向操作系统返回进程退出代码(ExitCode),直接结束当前进程并在应用程序事件薄中写入信息,用于程序出现致命错误需要立即停止。 Process.Kill:从名字也可以看出来,直接杀掉,不给喘息喘息机会,Kill方法会直接结束整个进程,不进行常规资源清理(什么finally块等……)。Kill本质调用本地API:TerminateProcess函数。 from:http://blog.csdn.net/nncrystal/article/details/36422785
View DetailsWPF在样式定义和UI动画上面相对于以前的技术有了不少的提升,下面给出WPF技术实现钟表的效果: 1、Visual Studio新建一个WPF应用程序,命名为WpfClock,新建一个images文件夹,并准备一个钟表的背景图片和程序图标素材。 2、编辑MainWindow.xaml文件,对UI进行定制,代码如下(指针都是用Rectangle实现的,当然可以用图片代替):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<Window x:Class="WpfClock.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Margin="2" Height="327" Width="311" AllowsTransparency="True" WindowStyle="None" Background="Transparent" WindowStartupLocation="CenterScreen" Icon="images/clock.ico" ResizeMode="NoResize" Topmost="False" Opacity="1"> <Grid Width="300" Height="300" MouseLeftButtonDown="Grid_MouseLeftButtonDown"> <Image Source="images/backGround.png"></Image> <Label Name="lab商标" Foreground="White" Margin="0,0,0,211" HorizontalAlignment="Center" VerticalAlignment="Bottom" Height="Auto" Width="Auto" FontSize="13" >JackMoon</Label> <Label Name="lab创建时间" Foreground="White" Margin="0,91,0,0" HorizontalAlignment="Center" VerticalAlignment="Top" Height="Auto" Width="Auto">1987</Label> <!-- 秒针定义 --> <Rectangle Margin="150,0,149,150" Name="rectangleSecond" Stroke="White" Height="120" VerticalAlignment="Bottom" Width="1"> <Rectangle.RenderTransform> <RotateTransform x:Name="secondPointer" CenterX="0" CenterY="120" Angle="0" /> </Rectangle.RenderTransform> </Rectangle> <!-- --> <!-- 分钟定义 --> <Rectangle Margin="150,49,149,151" Name="rectangleMinute" Stroke="LightGreen" Width="1"> <Rectangle.RenderTransform> <RotateTransform x:Name="minutePointer" CenterX="0" CenterY="100" Angle="45" /> </Rectangle.RenderTransform> </Rectangle> <!-- --> <!-- 时针定义 --> <Rectangle Margin="150,80,149,150" Name="rectangleHour" Stroke="LightYellow" Width="1"> <Rectangle.RenderTransform> <RotateTransform x:Name="hourPointer" CenterX="0" CenterY="70" Angle="90" /> </Rectangle.RenderTransform> </Rectangle> <!----> <Label Content="08:08:08" FontSize="16" Foreground="White" Height="Auto" HorizontalAlignment="Center" Margin="114,0,113,86" Name="labTime" VerticalAlignment="Bottom" Width="Auto" /> </Grid> </Window> |
3、编辑MainWindow.xaml.CS文件,对后台逻辑进行定制,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
using System; using System.Collections.Generic; using System.Linq; 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; namespace WpfClock { using System.Threading; using System.Windows.Threading; /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { //计时器 System.Timers.Timer timer = new System.Timers.Timer(1000); public MainWindow() { InitializeComponent(); #region 初始化时间 secondPointer.Angle = DateTime.Now.Second * 6; minutePointer.Angle = DateTime.Now.Minute * 6; hourPointer.Angle = (DateTime.Now.Hour * 30) + (DateTime.Now.Minute * 0.5); this.labTime.Content = DateTime.Now.ToString("HH:mm:ss"); #endregion timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed); timer.Enabled = true; } private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { //进行拖放移动 this.DragMove(); } private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { //UI异步更新 this.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => { //秒针转动,秒针绕一圈360度,共60秒,所以1秒转动6度 secondPointer.Angle = DateTime.Now.Second * 6; //分针转动,分针绕一圈360度,共60分,所以1分转动6度 minutePointer.Angle = DateTime.Now.Minute * 6; //时针转动,时针绕一圈360度,共12时,所以1时转动30度。 //另外同一个小时内,随着分钟数的变化(绕一圈60分钟),时针也在缓慢变化(转动30度,30/60=0.5) hourPointer.Angle = (DateTime.Now.Hour * 30)+ (DateTime.Now.Minute * 0.5); //更新时间值 this.labTime.Content = DateTime.Now.ToString("HH:mm:ss"); })); } } } |
4、编译运行,如果运气不错的话,应该能显示如下效果: 5、总结 WPF可以用RotateTransform中的Angle进行旋转,可以指定中心点(CenterX,CenterY)
1 2 3 |
<Rectangle.RenderTransform> <RotateTransform x:Name="hourPointer" CenterX="0" CenterY="70" Angle="90" /> </Rectangle.RenderTransform> |
from:https://www.cnblogs.com/isaboy/p/wpfclock.html
View Details简介 但凡涉及到图形界面,往往的设计都是不支持或者不推荐使用多个线程操作界面内容.而且通常会有一个专门的线程调度器来处理任务线程和界面线程的问题.下面提供两个两个方案. 使用Dispatcher.BeginInvoke 这个方法简单暴力适合小工作量的修改一些界面内容.使用Dispatcher.BeginInvoke()会将代码安排为调度程序的一个任务. 步骤 使用Thread新建并开始一个线程 在新建的线程处理函数中需要修改界面的时候获取界面的dispatcher 使用Dispatcher的BeginInvoke方法指定一个线程优先级,和一个委托,这个委托时用于修改界面内容的 下面给出一部分代码
1 2 3 |
//新建线程 Thread thread = new Thread(UpdateTextRight); thread.Start(); |
下面是新线程中的方法
1 2 3 4 5 6 7 8 9 10 |
//这个事例刚好是先窗体类中定义的,所以获取Dispatcher变得比较方便,而且使用了匿名委托.在通常的代码中会把委托给分离出去比较好. private void UpdateTextRight() { this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) delegate() { txt.Text = "Here is some new text."; } ); } |
使用BackgroupWorker 这个类是专门用于简化Windows Form程序与线程相关的问题设计的,同样适用于WPF程序.适合于一个长期的后台进程,支持进度通知,取消支持,完成通知等功能. 使用方法也很简单,创建一个BackfruopWorker实例,它有几个事件. DoWork事件会在另外一个线程中执行,用RunWorkerAsync()启动.所以在这个事件中不要去处理修改界面的事情 RunWorkerCompleted事件,在DoWork事件返回时(正常或者异常返回),在图形的线程中执行,所以可以修改界面 ProgressChanged事件,使用ReportProgress()方法调用,同时是在图形界面的线程中执行,通常负责修改一下进度条什么的.而ReportProgress()方法,通常会在DoWork的事件中调用,然后给一个百分比的值.要使用这个功能,需要把WorkerReportsProgress属性设置成true 另外值得一说的是,要取消支持需要把WorkerSupportsCancellation属性设为true,使用CancelAsync()方法调用,但是这个调用不会终止进程,所以在DoWork事件中需要判断CancellationPending. 下面给出部分代码 创建BackgroundWorker实例
1 2 3 4 5 6 7 8 9 10 11 |
BackgroundWorker backgroundWorker; backgroundWorker = new BackgroundWorker(); backgroundWorker.DoWork += backgroundWorker_DoWork; backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted; //可以返回工作进度 backgroundWorker.WorkerReportsProgress = true; backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged; //允许取消 backgroundWorker.WorkerSupportsCancellation = true; |
开始执行DoWork
1 |
backgroundWorker.RunWorkerAsync(); |
DoWork事件范例,这个方法的内容是在另外一个线程,异步执行得
1 2 3 4 5 6 7 8 9 10 11 |
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { while(!backgroundWorker.CancellationPending) { //Do SomeThing //在合适的时候使用 //backgroundWorker.ReportProgress(i); //报告一下进度,其中i是0-100的整数 } //这里可以使用e.Result给一个返回值,如果有需要的话 } |
进度改变时的处理事件,也就是修改一下进度条什么的
1 2 3 4 |
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) { progressBar.Value = e.ProgressPercentage; } |
完成事件我就不演示,下面是取消任务的方法
1 2 3 4 |
private void cmdCancel_Click(object sender, RoutedEventArgs e) { backgroundWorker.CancelAsync(); } |
https://www.cnblogs.com/atskyline/archive/2012/06/22/2558516.html
View Details