BackgroundWorker - Report Time - c#

I have a control on my GUI which I would like to make visible only case when I run BackgroundWorkers (many different operations). Some of these operations last less than 500ms, and I feel that making the control visible for so short a time is useless. Therefore, I would like to make the control visible only if a BackgroundWorker has already been working for 500ms.

Just start a timer at the same time you start the BGW:
private void button1_Click(object sender, EventArgs e) {
timer1.Enabled = true;
backgroundWorker1.RunWorkerAsync();
}
private void timer1_Tick(object sender, EventArgs e) {
timer1.Enabled = false;
myControl1.Visible = true;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
timer1.Enabled = myControl1.Visible = false;
}

Leverage the ReportProgress method on the BackgroundWorker. You can place whatever you want in the state parameter and then perform the calculation accordingly.
public class MyObject
{
public DateTime TimeStarted {get; set;}
}
Then in your ProgressChanged event handler...
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if(DateTime.Now.Subtract(((MyObject)e.UserState).TimeStarted).TotalMilliseconds > 500)
{
//show your control
}
}

You can use a Timer inside the BackgroundWorker and call the ReportProgress method once 500ms have passed.
In the UI thread you then just need to handle the ProgressChanged event and show/hide your control as required.
public partial class Form1 : Form
{
/// <summary>
/// Timer.
/// </summary>
private Timer timer = new Timer();
/// <summary>
/// Initializes a new instance of the <see cref="Form1"/> class.
/// </summary>
public Form1()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.DoWork += BackgroundWorker1DoWork;
backgroundWorker1.ProgressChanged += BackgroundWorker1ProgressChanged;
timer.Interval = 500;
timer.Tick += TimerTick;
}
/// <summary>
/// Handles the Tick event of the timer control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
void TimerTick(object sender, EventArgs e)
{
timer.Enabled = false;
backgroundWorker1.ReportProgress(99);
}
/// <summary>
/// Handles the Click event of the button1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void Button1Click(object sender, EventArgs e)
{
timer.Enabled = true;
backgroundWorker1.RunWorkerAsync();
}
/// <summary>
/// Handles the DoWork event of the backgroundWorker1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.ComponentModel.DoWorkEventArgs"/> instance containing the event data.</param>
private void BackgroundWorker1DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
// Do your work...
Thread.Sleep(2000);
}
/// <summary>
/// Handles the ProgressChanged event of the backgroundWorker1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.ComponentModel.ProgressChangedEventArgs"/> instance containing the event data.</param>
private void BackgroundWorker1ProgressChanged(object sender, ProgressChangedEventArgs e)
{
label1.Visible = (e.ProgressPercentage == 99);
}
}

Related

Workbook.Close is not firing WorkbookBookBeforeClose Event in Excel Addins C#

In my ThisAddins.cs am having WorkbookBookBeforeClose Event and am having one button event in Ribbon.cs file in that i written workbook.close (true,workbook.fullname,null) it is not firing the
WorkbookBookBeforeClose Event while working with Multiple file.
Is there anything having to follow for calling workbookBeforeClose Event?
The following code works fine on my side:
public partial class ThisAddIn
{
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
this.Application.WorkbookBeforeClose += ApplicationOnWorkbookBeforeClose;
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}
// Catch the before close event
private void ApplicationOnWorkbookBeforeClose(Excel.Workbook wb, ref bool cancel)
{
MessageBox.Show("ApplicationOnWorkbookBeforeClose");
}
#region VSTO generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
}
#endregion
}

How to add a SelectedValueChanging event to combobox

I need to inherit for ComboBox in order to add a new event OnSelectedValueChanging().
This event should be triggered when the user is attempting to change the current selected value of the combo box.
This event also should be cancellable (the user has the ability to use e.cancel as in the FormClosing event for example)
public class SUIComboBox : UIComboBox
{
/// <summary>
/// The prevously selected value
/// </summary>
private object _PreviousSelectedValue = null;
public event EventHandler<EventArgs> SelectedValueChanging;
protected virtual void OnSelectedValueChanging(object sender, CancelEventArgs e)
{
var handler = SelectedValueChanging;
handler?.Invoke(sender, e);
}
}
public class SelectedValueChangingEventArgs : CancelEventArgs
{
}

GridView lost search result after change page size or click on paging?

I have a gridview to show the data and and text box to do the search. When i search, the gridview could show the data correctly, but when I click on change page size or go to next page, the gridview will reload to the original state. Is there anything to do with the ViewState? Appreciate is someone could help. following is my code:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ddPageSize_SelectedIndexChanged(object sender, EventArgs e)
{
// handle event
DropDownList ddpagesize = sender as DropDownList;
GridView1.PageSize = Convert.ToInt32(ddpagesize.SelectedItem.Text);
ViewState["PageSize"] = ddpagesize.SelectedItem.Text;
GridView1.DataBind();
}
protected void btnSearch_Click(object sender, EventArgs e)
{
SqlDataSource1.SelectCommand = "" + txtSearchValue.Text + "'";
GridView1.DataBind();
}
protected void btnReload_Click(object sender, EventArgs e)
{
txtSearchValue.Text = "";
lblSearchError.Text = "";
GridView1.DataBind();
}
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
row.Attributes["onmouseover"] =
"this.style.backgroundColor;this.style.backgroundColor='#AED4EB';";
row.Attributes["onmouseout"] =
"this.style.textDecoration='none';this.style.background='#ffffff';";
// Set the last parameter to True
// to register for event validation.
row.Attributes["onclick"] =
Page.ClientScript.GetPostBackClientHyperlink(GridView1,
"Select$" + row.DataItemIndex, true);
}
}
base.Render(writer);
}
protected void btnDate_Click(object sender, EventArgs e)
{
SqlDataSource1.SelectCommand = "";
GridView1.DataBind();
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
int rowindex = GridView1.SelectedIndex % GridView1.PageSize;
GridViewRow row = GridView1.Rows[rowindex];
Session["TSO"] = row.Cells[7].Text.Trim();
string url = "http://localhost:60918/Requests.aspx";
StringBuilder sb = new StringBuilder();
sb.AppendLine("<script type='text/javascript'>");
sb.AppendLine("window.open('" + url + "')");
sb.AppendLine("<" + "/script>");
ScriptManager.RegisterStartupScript(upGrdCustomers, upGrdCustomers.GetType(), "myjs", sb.ToString(), false);
}
catch (System.Threading.ThreadAbortException)
{
throw;
}
}
Here is my code for the GridView:
[ToolboxData("<{0}:GridView runat=server></{0}:GridView>")]
public class GridView : System.Web.UI.WebControls.GridView, IPageableItemContainer
{
/// <summary>
/// TotalRowCountAvailable event key
/// </summary>
private static readonly object EventTotalRowCountAvailable = new object();
/// <summary>
///
/// </summary>
/// <param name="dataSource"></param>
/// <param name="dataBinding"></param>
/// <returns></returns>
protected override int CreateChildControls(IEnumerable dataSource, bool dataBinding)
{
int rows = base.CreateChildControls(dataSource, dataBinding);
// if the paging feature is enabled, determine
// the total number of rows in the datasource
if (this.AllowPaging)
{
// if we are databinding, use the number of rows that were created,
// otherwise cast the datasource to an Collection and use that as the count
int totalRowCount = dataBinding ? rows : ((ICollection)dataSource).Count;
// raise the row count available event
IPageableItemContainer pageableItemContainer = this as IPageableItemContainer;
this.OnTotalRowCountAvailable(
new PageEventArgs(
pageableItemContainer.StartRowIndex,
pageableItemContainer.MaximumRows,
totalRowCount
)
);
// make sure the top and bottom pager rows are not visible
if (this.TopPagerRow != null)
{
this.TopPagerRow.Visible = false;
}
}
return rows;
}
#region IPageableItemContainer Interface
/// <summary>
///
/// </summary>
/// <param name="startRowIndex"></param>
/// <param name="maximumRows"></param>
/// <param name="databind"></param>
void IPageableItemContainer.SetPageProperties(
int startRowIndex, int maximumRows, bool databind)
{
int newPageIndex = (startRowIndex / maximumRows);
this.PageSize = maximumRows;
if (this.PageIndex != newPageIndex)
{
bool isCanceled = false;
if (databind)
{
// create the event args and raise the event
GridViewPageEventArgs args = new GridViewPageEventArgs(newPageIndex);
this.OnPageIndexChanging(args);
isCanceled = args.Cancel;
newPageIndex = args.NewPageIndex;
}
// if the event wasn't cancelled
// go ahead and change the paging values
if (!isCanceled)
{
this.PageIndex = newPageIndex;
if (databind)
{
this.OnPageIndexChanged(EventArgs.Empty);
}
}
if (databind)
{
this.RequiresDataBinding = true;
}
}
}
/// <summary>
///
/// </summary>
int IPageableItemContainer.StartRowIndex
{
get { return this.PageSize * this.PageIndex; }
}
/// <summary>
///
/// </summary>
int IPageableItemContainer.MaximumRows
{
get { return this.PageSize; }
}
/// <summary>
///
/// </summary>
event EventHandler<PageEventArgs> IPageableItemContainer.TotalRowCountAvailable
{
add { base.Events.AddHandler(GridView.EventTotalRowCountAvailable, value); }
remove { base.Events.RemoveHandler(GridView.EventTotalRowCountAvailable, value); }
}
/// <summary>
///
/// </summary>
/// <param name="e"></param>
protected virtual void OnTotalRowCountAvailable(PageEventArgs e)
{
EventHandler<PageEventArgs> handler = (EventHandler<PageEventArgs>)base.Events[GridView.EventTotalRowCountAvailable];
if (handler != null)
{
handler(this, e);
}
}
#endregion
}
}
In your server side event handler called ddPageSize_SelectedIndexChanged you are calling Databind on your grid without checking if there is a search term entered and setting that on the DataSource of the Grid.
protected void ddPageSize_SelectedIndexChanged(object sender, EventArgs e)
{
...
SqlDataSource1.SelectCommand = "" + txtSearchValue.Text + "'";
GridView1.DataBind();
}
Try this. When you change the pagesize it triggers a postback and leaving the value for SelectCommand as empty resulting the gridview to load in it's original state. Set it to txtSearchValue.Text and try
protected void ddPageSize_SelectedIndexChanged(object sender, EventArgs e)
{
// handle event
DropDownList ddpagesize = sender as DropDownList;
GridView1.PageSize = Convert.ToInt32(ddpagesize.SelectedItem.Text);
ViewState["PageSize"] = ddpagesize.SelectedItem.Text;
SqlDataSource1.SelectCommand = "" + txtSearchValue.Text + "'";
GridView1.DataBind();
}

How can I keep all the focused forms?

I've an application that use two forms: Form1 (main) and Form2 (secondary). I show the Form2 with the following code:
Form2 frm = new Form2();
frm.TopMost = true;
frm.Show();
When the Form2 is visible, it hasn't the focus. How can I do the focus at the Form2 and keep the focus at the Form1? Sorry for my bad english!
try bellow code within MDI Parent Form (Main Form)
private Form2 _form2;
#region UtilOpenForm
/// <summary>
/// UtilOpenForm
/// </summary>
/// <param name="appContainer"></param>
/// <param name="childForm"></param>
private void UtilOpenForm(Form appContainer, Form childForm)
{
this.Cursor = Cursors.WaitCursor;
if (childForm == null)
{
throw new ArgumentNullException("childForm");
}
childForm.MdiParent = appContainer;
childForm.StartPosition = FormStartPosition.CenterScreen;
childForm.MaximizeBox = false;
childForm.MinimizeBox = false;
childForm.Closed += new EventHandler(childForm_Closed);
childForm.Show();
this.Cursor = Cursors.Default;
}
Now from Button / Menu click within MDI Parent
if (_form2 == null)
{
UtilOpenForm(this, _form2 = new Form2());
}
Now child form close Function within MDI Parent
#region childForm_Closed
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void childForm_Closed(object sender, EventArgs e)
{
if (sender.GetType() == typeof(Form2))
{
_form2.Dispose();
if (_form2 != null)
{
_form2 = null;
}
}

Drag and drop a path in a wpf

Is it possible to drag and drop a path in a wpf using Mouse Eventhandlers? In partcular I want to drag a path with the left mouse button and to mouse it on the grid. How can this be done?
Try this:
Given:
TextBox name is "TextBox1"
public MainWindow()
{
// Initialize UI
InitializeComponent();
// Loaded event
this.Loaded += delegate
{
TextBox1.AllowDrop = true;
TextBox1.PreviewDragEnter += TextBox1PreviewDragEnter;
TextBox1.PreviewDragOver += TextBox1PreviewDragOver;
TextBox1.Drop += TextBox1DragDrop;
};
}
/// <summary>
/// We have to override this to allow drop functionality.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void TextBox1PreviewDragOver(object sender, DragEventArgs e)
{
e.Handled = true;
}
/// <summary>
/// Evaluates the Data and performs the DragDropEffect
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void TextBox1PreviewDragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effects = DragDropEffects.Copy;
}
else
{
e.Effects = DragDropEffects.None;
}
}
/// <summary>
/// The drop activity on the textbox.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void TextBox1DragDrop(object sender, DragEventArgs e)
{
// Get data object
var dataObject = e.Data as DataObject;
// Check for file list
if (dataObject.ContainsFileDropList())
{
// Clear values
TextBox1.Text = string.Empty;
// Process file names
StringCollection fileNames = dataObject.GetFileDropList();
StringBuilder bd = new StringBuilder();
foreach (var fileName in fileNames)
{
bd.Append(fileName + "\n");
}
// Set text
TextBox1.Text = bd.ToString();
}
}

Categories