backgroundworker实现进度条显示实…

1. 从工具栏拖一个BackgroundWorker控件,设置其属性WorkerReportsProgress为true

2. 要让worker开始工作,执行如下代码:
    mBackgroundWorker.RunWorkerAsync(arg);
    这里有重写,如果不需要传递参数直接mBackgroundWorker.RunWorkerAsync();

3. 编辑DoWork事件代码:
    e.Argument为mBackgroundWorker.RunWorkerAsync(arg);对应的参数
    之所以使用进度条,肯定是有循环的,在循环中报告进度:
    worker.ReportProgress(i * 100 / totalNum, obj );
    其中第一个参数是当前进度的百分之多少,obj为你要传递的UserState,如果没有可以不要

4. 编辑ProgressChanged事件代码:
    e.ProgressPercentage为进度的百分数,e.UserState为刚才传递过来的object
    在这个事件中可以调用ui的进度条和其他控件:
    mToolStripProgressBar.Value = e.ProgressPercentage;

5. 编辑RunWorkerCompleted事件代码:
    工作完成了告诉ui


示例代码:一个简单的刷网页流量的小工具

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Threading;

namespace shua
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync(textBox1.Text);
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = (BackgroundWorker)sender;
            string url = e.Argument.ToString();
            int num = int.Parse(textBox2.Text);
            for (int i = 0; i < num; i++)
            {
                if (!worker.CancellationPending)
                {
                    WebRequest request = WebRequest.Create(url);
                    WebResponse response = request.GetResponse();
                    response.Close();
                   
                    Thread.Sleep(100);
                    worker.ReportProgress(i * 100 / num, i);
                }
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
            label3.Text = e.UserState.ToString();
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("ok");
        }
    }
}

 

1. 如何创建一个可改变大小没有标题栏的窗体?(How to create a form with resizing borders and no title bar?)

form1.Text = string. Empty;
form1.ControlBox = false;


2. 如何在.NET的Windows窗体上启用XP主题集?(How to use XP Themes with Windows Forms using the .NET?)

确认你的控件中FlatStyle属性已经修改为System,再修改Main方法。

static void Main()
{
  Application.EnableVisualStyles();
  Application.DoEvents();
  Application. Run(new Form1());
}


3. 如何为一个窗体设置一个默认按钮?(How to set the default button for a form?)

form1.AcceptButton = button1;

4. 如何为一个窗体设置一个取消按钮?(How to set the Cancel button for a form?)

form1.CancelButton = button1;

5. 如何阻止一个窗体标题显示在任务栏上?(How to prevent a form from being shown in the taskbar?)

设置窗体的ShowIntaskbar属性为False

6. 如何用现有可用字体绑定到ComboBox控件?(How to fill a ComboBox with the available fonts?)

comboBox1.Items.AddRange (FontFamily.Families);

7. 如何禁止TextBox控件默认的邮件菜单?(How to disable the default ContextMenu of a TextBox?)

textBox1.ContextMenu = new ContextMenu ();

8. 如何获取“我的文档”等一些系统文件夹路径?(How to get the path for "My Documents" and other system folders?)

Environment.SpecialFolder中包含了一些系统文件夹信息
MessageBox.Show(Environment.GetFolderPath( Environment.SpecialFolder.Personal ));

9. 如何获取应用程序当前执行的路径?(How to get the path to my running EXE?)

string appPath = Application.ExecutablePath;

10. 如何确定当前运行的系统?(How to determine which operating system is running?)

OperatingSystem os = Environment.OSVersion;
MessageBox.Show(os.Version.ToString());
MessageBox.Show(os.Platform.ToString());

11. 如何从完整的路径中获取文件名?(How to get a file's name from the complete path string?)

用System.IO.Path.GetFileName 和 System.IO.Path.GetFileNameWithoutExtension(无扩展名)的方法

12. 如何从完整的路径中获取文件扩展名?(How to get a file's extension from the complete path string?)

用System.IO.Path.GetExtension方法

13. 如何使没有选择日期的DateTimePicker控件为空文本?(How to make the DateTimePicker show empty text if no date is selected?)

dateTimePicker1.CustomFormat = " ";
dateTimePicker1.Format = DateTimePickerFormat.Custom;

14. 如何在Report Viewer中隐藏Crystal Report的状态栏?(How to hide the status bar of Crystal Report in Report Viewer?)

foreach(object obj in this.crystalReportViewer1.Controls)
   
  if( obj.GetType()== typeof(System.Windows.Forms.StatusBar))
    
  StatusBar sBar=(StatusBar)obj;
  sBar.Visible=false;
    
}


15. 如何利用Crystal Report程序来生成PDF版本?(How to generate PDF version of Crystal Report programmatically?)

ReportDocument O_Report=new ReportDocument();
ExportOptions exportOpts = new ExportOptions();
PdfRtfWordFormatOptions pdfFormatOpts = new PdfRtfWordFormatOptions ();
DiskFileDestinationOptions diskOpts = new DiskFileDestinationOptions();
exportOpts = O_Report.ExportOptions;
// 设置PDF格式  
exportOpts.ExportFormatType = ExportFormatType.PortableDocFormat;
exportOpts.FormatOptions = pdfFormatOpts;
// 设置文件选项和导出
exportOpts.ExportDestinationType = ExportDestinationType.DiskFile;
diskOpts.DiskFileName = "C://Trial.pdf"; //设置PDF导出路径   
exportOpts.DestinationOptions = diskOpts;
O_Report.Export ();


16.通过代码如何输入多行文本?(How to enter multiline text in textbox through code? )

利用TextBox控件的LINES属性
string [] strAddress = {"Mukund Pujari","Global Transformation Technologies","Pune, India"};
textBox1.MultiLine=true;
textBox1.Lines=strAddress;

或者
textBox1.Text="Line 1\r\nLine2\r\nLine3.";

或者
用"System.Environment.NewLine"来替代换行符号

17. 如何在DataGrid中去掉CheckBox不确定状态?(How to remove the indeterminate status of checkbox in datagrid?)

DataGridTableStyle ts1 = new DataGridTableStyle(); //创建Table样式
ts1.MappingName = "Items"; //分配要应用样式的Data Table
DataGridColumnStyle boolCol = new DataGridBoolColumn(); // 创建CheckBox列
boolCol.MappingName = "ch"; //分配数据列名称
boolCol.AllowNull=false; // 修改AllowNull属性

18. 如何在用一个数据源DataTable绑定两个控件,确保变化不反映在两个控件中?( How to bind two controls to the same DataTable without having changes in one control also change the other control?)

我们在一个Form中放置一个ListBox和一个ComboBox控件,当数据源是一个DataTable而且绑定的ValueMember一致的时候我们选择ListBox中的一个Item时,ComboBox控件中的相同的Item也会被自动选中,我们可以采取建立新的上下文绑定对象来拒绝这样的同步操作
comboBox1.DataSource = dataset.Tables[ "Items" ];
comboBox1.ValueMember = "CustomerID";
comboBox1.DisplayMember = "CustomerID";

listBox1.BindingContext = new BindingContext(); // 设置新的上下文绑定对象
listBox1.DataSource = dataset.Tables[ "Items" ];
listBox1.ValueMember = "CustomerID";
listBox1.DisplayMember = "CustomerID";

19. 一个简单的创建链接字符串的方法。(An easy way to build connection string.)

记事本创建一个New.udl的文件,一个Microsoft 数据链接文件
双击打开,熟悉吧
按照向导创建完成一个数据库链接,测试成功
确定后,链接字符串写入这个文件,用记事本打开就看到了

20. 如何打开客户端E-Mail程序,Windows应用和Web应用?( How to open default E-mail client on your system with all parameters entered in it,like Outlook Express or Eudora, from your .NET windows or Web Application? )

Web Application:
A href="mailto:email@address1.com,email@address2.com?cc=email@address3.com&Subject=Hello&body=Happy New Year"

Windows Application:
引用System.Diagnostics.Process 命名空间
Process process = new Process();
process.StartInfo.FileName = "mailto:email@address1.com,email@address2.com?subject=Hello&cc=email@address3.com
&bcc=email@address4.com&body=Happy New Year" ;
process.Start();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值