c# webbrowser viewer control takes time to dispose - c#

When closing Form containing a WebBrowser control with a Pdf document open in the webbrowser, the form takes some 10 seconds to close. I tracked the issue down to Dispose method of the webbrowser.
private void advBandedGridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
{
if (advBandedGridView1.GetFocusedDataRow() != null)
{
string wordno = advBandedGridView1.GetFocusedDataRow()["wordno"].ToString();
string itemcd = advBandedGridView1.GetFocusedDataRow()["itemcd"].ToString();
for (int i = 0; i < _caseCount; i++)
{
ButtonColoring(wordno, _seqkindCode[i]);
}
LoadPDF(itemcd);
gridControl2.DataSource = null;
gridControl2.RefreshDataSource();
}
}
Control Event
private void LoadPDF(string itemcd)
{
try
{
ReturnPacket rp;
rp = new Q3i.POP.BIZ.Common.CommonCode().SelectCommonCodeFull("603", "kind3 = 'EYE'", false);
if (rp.DataTables.Count > 0 && rp.DataTables[0].Rows.Count == 0)
{
rp = new Q3i.POP.BIZ.Common.CommonCode().SelectCommonCodeFull("603", "kind3 = '1'", false);
}
if (rp.DataTables[0].Rows.Count > 0)
{
string dockind = string.Empty;
dockind = rp.DataTables[0].Rows[0]["code"].ToString();
ParameterCollection paramCol = new ParameterCollection();
paramCol.Add("p_itemcd", itemcd);
paramCol.Add("p_dockind", dockind);
PdfFileInfo temp_fileInfo = biz.SelectInspectionStandards(paramCol);
if (temp_fileInfo != null)
{
if (_fileInfo != null && temp_fileInfo.FileNm == _fileInfo.FileNm)
{
WebBrowserPdf.Visible = true;
return;
}
_fileInfo = null;
_fileInfo = temp_fileInfo;
PDF_FILE_PATH = FilePath + _fileInfo.FileNm;
DirectoryInfo di = new DirectoryInfo(FilePath);
if (di.Exists == false)
{
di.Create();
}
if (!File.Exists(PDF_FILE_PATH))
File.WriteAllBytes(PDF_FILE_PATH, _fileInfo.FileData);
if (!PDF_FILES.Contains(PDF_FILE_PATH))
{
PDF_FILES.Add(PDF_FILE_PATH);
}
WebBrowserPdf.Navigate(PDF_FILE_PATH + "?#zoom=" + _zoomFactor + "%", false);
WebBrowserPdf.Visible = true;
simpleButtonOpenPOPUP.Enabled = true;
}
else
{
WebBrowserPdf.Visible = false;
simpleButtonOpenPOPUP.Enabled = false;
}
}
}
catch (Exception ex)
{
UCXtraMsgBox.ShowDialog(ex.Message, "m0146", Q3i.Common.Enums.MsgBoxButton.OK, Q3i.Common.Enums.MsgBoxIcon.Alert, true);
}
}
it is Load Method
private void w_pcmu081_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
WebBrowserPdf.Dispose();
Process[] Pro = Process.GetProcessesByName("osk");
if (Pro.GetLength(0) > 0)
Pro[0].Kill();
}
catch(Exception ex)
{
UCXtraMsgBox.ShowDialog(ex.Message, "m0146", Q3i.Common.Enums.MsgBoxButton.OK, Q3i.Common.Enums.MsgBoxIcon.Info, true, null, true);
}
}
Closing

The same situation happened to me.
Adobe has done something wrong in the latest version of Acrobat Reader DC (15.023.20056).
If you uncheck option Enable Protected Mode at startup in Edit -> Preferences -> Security (Enhanced), everything will be back to normal.
On my case it is not a solution.
More info here: https://forums.adobe.com/thread/2267688

Related

Unable to check all check boxes in a GridView

I am using grid view check box to select all the values in the grid view when i click the check box, but the problem i am facing is it is selecting the only the first page value how ever i have coded to bring all the values in but in design it is not working out
this is the image
i want all the check box to checked in design when i press the all check button.
protected void gvBatch_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType != DataControlRowType.Header && e.Row.RowType != DataControlRowType.Footer && e.Row.RowType != DataControlRowType.Pager)
{
DropDownList ddlcountry1 = (DropDownList)e.Row.FindControl("ddlcountry");
populateLocationValues(ddlcountry1);
{
ArrayList checkboxvalues = (ArrayList)Session["BP_PrdId"];
//string Bp_Id = "";
if (checkboxvalues != null && checkboxvalues.Count > 0)
{
string strBp_Id = ((HiddenField)e.Row.FindControl("hf_ProductLblId")).Value.ToString();
if (checkboxvalues.Contains(strBp_Id))
{
CheckBox myCheckBox = (CheckBox)e.Row.FindControl("chkPLPSltItem");
myCheckBox.Checked = true;
}
}
}
DataSet dsaccess = MenuRestriction();
DataRow dr = null;
string sView = "";
string sEdit = "";
string sInsert = "";
string sDeactive = "";
if (dsaccess.Tables.Count > 0)
{
if (dsaccess.Tables[0].Rows.Count > 0)
{
dr = dsaccess.Tables[0].Rows[0];
sView = dr["MnuRgts_View"].ToString();
sEdit = dr["MnuRgts_Edit"].ToString();
sInsert = dr["MnuRgts_Insert"].ToString();
sDeactive = dr["MnuRgts_DeActivate"].ToString();
if (sInsert == "Y" && sDeactive == "Y")
{
BtnDelete.Visible = true;
imgNew.Visible = true;
}
else
{
BtnDelete.Visible = false;
imgNew.Visible = false;
if (sInsert == "Y")
{
imgNew.Visible = true;
}
if (sDeactive == "Y")
{
BtnDelete.Visible = true;
}
}
}
}
}
}
catch (Exception ex)
{
log.Error("gvBatch_RowDataBound", ex);
}
}
protected void gvBatch_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
RememberOldValues();
gvBatch.PageIndex = e.NewPageIndex;
//RetrieveValues();
BindGrid();
LoadLocation();
//RePopulateValues();
}
private void RememberOldValues()
{
ArrayList checkboxvalues = new ArrayList();
string strBp_Id = "";
foreach (GridViewRow row in gvBatch.Rows)
{
//index = (int)gvBatch.DataKeys[row.RowIndex].Value;
strBp_Id = ((HiddenField)row.FindControl("hf_ProductLblId")).Value.ToString();
bool result = ((CheckBox)row.FindControl("chkPLPSltItem")).Checked;
// Check in the Session
if (Session["BP_PrdId"] != null)
checkboxvalues = (ArrayList)Session["BP_PrdId"];
if (result)
{
if (!checkboxvalues.Contains(strBp_Id))
checkboxvalues.Add(strBp_Id);
}
else
{
if (checkboxvalues.Contains(strBp_Id))
checkboxvalues.Remove(strBp_Id);
}
}
if (checkboxvalues != null && checkboxvalues.Count > 0)
Session["BP_PrdId"] = checkboxvalues;
}
protected void gvBatch_PreRender(object sender, EventArgs e)
{
try
{
if (gvBatch.TopPagerRow != null)
{
((Label)gvBatch.TopPagerRow.FindControl("lbCurrentPage")).Text = (gvBatch.PageIndex + 1).ToString();
((Label)gvBatch.TopPagerRow.FindControl("lbTotalPages")).Text = gvBatch.PageCount.ToString();
((LinkButton)gvBatch.TopPagerRow.FindControl("lbtnFirst")).Visible = gvBatch.PageIndex != 0;
((LinkButton)gvBatch.TopPagerRow.FindControl("lbtnPrev")).Visible = gvBatch.PageIndex != 0;
((LinkButton)gvBatch.TopPagerRow.FindControl("lbtnNext")).Visible = gvBatch.PageCount != (gvBatch.PageIndex + 1);
((LinkButton)gvBatch.TopPagerRow.FindControl("lbtnLast")).Visible = gvBatch.PageCount != (gvBatch.PageIndex + 1);
DropDownList ddlist = (DropDownList)gvBatch.TopPagerRow.FindControl("ddlPageItems");
ddlist.SelectedIndex = ddlist.Items.IndexOf(ddlist.Items.FindByValue(ViewState["DropDownPageItems"].ToString()));
gvBatch.AllowPaging = true;
gvBatch.TopPagerRow.Visible = true;
}
}
catch (Exception ex)
{
}
}
protected void gvBatch_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "EDIT")
{
GridViewRow row = (GridViewRow)((Control)e.CommandSource).Parent.Parent;
string strAgentName = ((HiddenField)row.FindControl("hf_loginName")).Value.ToString();
if (strAgentName != "")
{
Response.Redirect("CustomerDetails.aspx?Name=" + strAgentName, false);
}
}
}
catch (Exception ex)
{
log.Error("gvAgentRowcommand_AgentSummary", ex);
}
}
You can keep a boolean field in your code and set its value to true whenever the select all is clicked. When loading new pages, you can check that field to automatically display all checked. The same can be done when exporting the grid also.
you can modify and use the following Method
private void selectAllChecksInDAtaGrid()
{
foreach (DataGridViewRow item in myDataGrid.Rows)
{
if (Convert.ToBoolean(item.Cells["Column_Name"].Value) == false)
{
item.Cells["Column_Name"].Value = true;
}
}
}
the 'Column_name' is the name of the checkbox column. if you haven'nt named it yet you can also use the index number .
in your case its 0
private void selectAllChecksInDAtaGrid()
{
foreach (DataGridViewRow item in myDataGrid.Rows)
{
if (Convert.ToBoolean(item.Cells[0].Value) == false)
{
item.Cells[0].Value = true;
}
}
}
You should update (ArrayList)Session["BP_PrdId"] to include all the "Id"s of datasource of gridview. then bind data again.

How to Send File to printer Directly Through Code in asp.net c# when web Application host on local server

This Code will work when code run from visual studio.
But Not work when host on local host. not call to printer.
protected void btnsave_Click(object sender, EventArgs e)
{
try
{
objBel.BillId = lblbillid.Text;
objBel.NetAmount = txtnetbillamt.Text;
objBel.PDiscount = txtdiscountpercentage.Text;
objBel.DiscountA = txtdiscountamount.Text;
objBel.TaxAmt = txttaxamount.Text;
objBel.PaymentMode = ddlpaymentMode.SelectedItem.Text;
if (ddlpaymentMode.SelectedItem.Text == "Cheque")
{
objBel.ChequeNo = txtchno.Text;
if (txtDate.SelectedDate != null)
{
objBel.ChequeDate = txtDate.SelectedDate.Value.ToString("dd-MM-yyyy");
}
objBel.ChequeDetails = txtotherdetails.Text;
}
if (rbyes.Checked)
{
objBel.ThirdParty = txtthirdpartydiscription.Text;
}
objBel.FinalAmt = txtfinalamount.Text;
objBel.UserId = Convert.ToInt32(Session["UserId"]);
objBel.Time = DateTime.Parse(DateTime.Now.ToString()).ToString("hh:mm tt");
int i = objBal.UpdateBill(objBel);
if (i > 0)
{
Session["Billid"] = "";
DataTable dt = new DataTable();
dt = objBal.BillGenrate(lblbillid.Text);
ReportDocument doc = new ReportDocument();
doc.Load(Server.MapPath("~/CrystalReport/BillPrint.rpt"));
doc.SetDataSource(dt);
if (File.Exists(HttpContext.Current.Server.MapPath("\\Billprints\\Invoice.txt")))
File.Delete(HttpContext.Current.Server.MapPath("\\Billprints\\Invoice.txt"));
string fileName = Server.MapPath("\\Billprints\\") + "Invoice.txt";
doc.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.Text, fileName);
doc.Refresh();
doc.PrintToPrinter(1, false, 0, 0);
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Error Occur Try Again !!')", true);
}
}
catch { }
}

How to Return QuickBooks Report Results to WPF DataGrid Items?

I'm querying QuickBooks Desktop for transactions within a specific date range. I'm using boilerplate, or what seems to be, code to assign the report data to a Transaction class and adding the properties of the Transaction class to a WPF DataGrid for review by the end user.
My AllItemsDataGrid is instantiated inside the user control from the XAML below:
<DataGrid Name="AllItemsDataGrid" AutoGenerateColumns="False" CanUserAddRows="False" IsReadOnly="True" Loaded="EntriesDataGrid_OnLoaded">
</DataGrid>
I create the report request, response, a report return and populate transactions into the DataGrid as follows:
private void EntriesDataGrid_OnLoaded(object sender, RoutedEventArgs e)
{
try
{
if (WalkReportRet != null)
{
var transactions = new List<Transaction>();
var transaction = new Transaction
{
TxnType = transaction.TxnType.ToString(),
TxnNumber = transaction.TxnNumber.ToString(),
TxnDate = transaction.TxnDate.Date(),
TxnName = transaction.TxnName.ToString(),
GLAccount = transaction.GLAccount.ToString(),
TxnAmount = transaction.TxnAmount.ToString(),
TxnCleared = transaction.TxnCleared.ToString(),
TxnSplit = transaction.TxnSplit.ToString()
};
}
return;
AllItemsDataGrid.ItemsSource = transactions;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
public void RunQuery(object sender, RoutedEventArgs e)
{
bool sessionBegun = false;
bool connectionOpen = false;
QBSessionManager sessionManager = null;
try
{
//Create Session Manager
sessionManager = new QBSessionManager();
//Create the request to obtain the Profit and Loss Summary Report
IMsgSetRequest requestMsgSet = sessionManager.CreateMsgSetRequest("US", 13, 0);
requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue;
BuildGeneralDetailReportQueryRq(requestMsgSet);
//Connect to QB Desktop and begin a Session
sessionManager.OpenConnection(
#"C:\Users\Public\Public Documents\Intuit\QuickBooks\Company Files\MyCompany.QBW",
"MyCompany");
connectionOpen = true;
sessionManager.BeginSession("", ENOpenMode.omDontCare);
sessionBegun = true;
IMsgSetResponse responseMsgSet = sessionManager.DoRequests(requestMsgSet);
sessionManager.EndSession();
sessionBegun = false;
sessionManager.CloseConnection();
connectionOpen = false;
WalkGeneralDetailReportQueryRs(responseMsgSet);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
finally
{
if (sessionBegun)
{
sessionManager.EndSession();
}
if (connectionOpen)
{
sessionManager.CloseConnection();
}
}
}
void BuildGeneralDetailReportQueryRq(IMsgSetRequest requestMsgSet)
{
IGeneralDetailReportQuery txQuery = requestMsgSet.AppendGeneralDetailReportQueryRq();
txQuery.GeneralDetailReportType.SetValue(ENGeneralDetailReportType.gdrtTxnListByDate);
txQuery.DisplayReport.SetValue(true);
txQuery.ORReportPeriod.ReportPeriod.FromReportDate.SetValue(StartDate.Value);
txQuery.ORReportPeriod.ReportPeriod.ToReportDate.SetValue(EndDate.Value);
}
void WalkGeneralDetailReportQueryRs(IMsgSetResponse responseMsgSet)
{
if (responseMsgSet == null) return;
IResponseList responseList = responseMsgSet.ResponseList;
if (responseList == null) return;
//if we sent only one request, there is only one response, we'll walk the list for this sample
for (int i = 0; i < responseList.Count; i++)
{
IResponse response = responseList.GetAt(i);
//check the status code of the response, 0=ok, >0 is warning
if (response.StatusCode >= 0)
{
//the request-specific response is in the details, make sure we have some
if (response.Detail != null)
{
//make sure the response is the type we're expecting
ENResponseType responseType = (ENResponseType) response.Type.GetValue();
if (responseType == ENResponseType.rtGeneralDetailReportQueryRs)
{
//upcast to more specific type here, this is safe because we checked with response.Type check above
IReportRet ReportRet = (IReportRet) response.Detail;
WalkReportRet(ReportRet);
}
}
}
}
}
void WalkReportRet(IReportRet ReportRet)
{
if (ReportRet == null) return;
if (ReportRet.ReportData != null)
{
if (ReportRet.ReportData.ORReportDataList != null)
{
for (int i35 = 0; i35 < ReportRet.ReportData.ORReportDataList.Count; i35++)
{
IORReportData ORReportData = ReportRet.ReportData.ORReportDataList.GetAt(i35);
if (ORReportData.DataRow != null)
{
if (ORReportData.DataRow != null)
{
if (ORReportData.DataRow.RowData != null)
{
}
if (ORReportData.DataRow.ColDataList != null)
{
for (int i36 = 0; i36 < ORReportData.DataRow.ColDataList.Count; i36++)
{
IColData ColData = ORReportData.DataRow.ColDataList.GetAt(i36);
}
}
}
}
if (ORReportData.TextRow != null)
{
if (ORReportData.TextRow != null)
{
}
}
if (ORReportData.SubtotalRow != null)
{
if (ORReportData.SubtotalRow != null)
{
if (ORReportData.SubtotalRow.RowData != null)
{
}
if (ORReportData.SubtotalRow.ColDataList != null)
{
for (int i37 = 0; i37 < ORReportData.SubtotalRow.ColDataList.Count; i37++)
{
IColData ColData = ORReportData.SubtotalRow.ColDataList.GetAt(i37);
}
}
}
}
if (ORReportData.TotalRow != null)
{
if (ORReportData.TotalRow != null)
{
if (ORReportData.TotalRow.RowData != null)
{
}
if (ORReportData.TotalRow.ColDataList != null)
{
for (int i38 = 0; i38 < ORReportData.TotalRow.ColDataList.Count; i38++)
{
IColData ColData = ORReportData.TotalRow.ColDataList.GetAt(i38);
}
}
}
}
}
}
}
}
How do I evaluate if the report results are null, and if they are not pass them into my AllItemsDataGrid.ItemSource? Am I better off creating a TransactionQuery instead?

WebBrowser Not Firing LoadComplete, but Navigating Firing

I have userControl(wpf)
public WebBrowserControl()
{
InitializeComponent();
_Browser = new WebBrowser();
_pipeClient = new NamedPipeClient<WebMessage>("TestPipe");
_pipeClient.ServerMessage += PipeClientOnServerMessage;
_pipeClient.Error += PipeClientOnError;
_pipeClient.Start();
InternetExplorerBrowserEmulation.SetBrowserEmulationMode();
SuppressScriptErrors(_Browser, false);
SetWebBrowserFeatures();
GridBrrw.Children.Add(_Browser);
_Browser.ObjectForScripting = new ObjectForScripting(_pipeClient);
_Browser.LoadCompleted += new LoadCompletedEventHandler(_Browser_OnLoadCompleted);
_Browser.Navigating += _Browser_OnNavigating;
var th = new Thread(ExecuteInForeground);
th.Start();
}
private void ExecuteInForeground()
{
int i = 0;
while (i<=9)
{
Thread.Sleep(1000);
_pipeClient.PushMessage(new WebMessage() {Actions = "allo"});
i++;
}
}
private void _Browser_OnNavigating(object sender, NavigatingCancelEventArgs e)
{
if (IsClick)
{
var mes = new WebMessage { Actions = "OpenUrl" };
mes.Url = e.Uri.AbsoluteUri;
_pipeClient.PushMessage(mes);
e.Cancel = false;
}
return;
e.Cancel = false;
}
private void _Browser_OnLoadCompleted(object sender, NavigationEventArgs e)
{
try
{
var br = sender as WebBrowser;
if (br?.Source != null && br.Source.AbsoluteUri != e.Uri.AbsoluteUri)
{
MessageBox.Show($"Source = {br.Source.AbsoluteUri},\r\n AbsoluteUri = {e.Uri.AbsoluteUri}");
return;
}
Document = (HTMLDocument)br.Document;
if (!string.IsNullOrEmpty(FindElement))
{
var node = HtmlNode.CreateNode(FindElement);
while (GetElement(node) == null)
{
System.Windows.Forms.Application.DoEvents();
}
}
if (WaitAjax)
{
ConnectToAjax();
return;
}
if (Sleep > 0)
{
var time = TimeSpan.FromSeconds(Sleep);
Thread.Sleep(time);
}
var mes = new WebMessage { Actions = "Load" };
mes.Title = Document.title;
mes.Url = br.Source.AbsoluteUri;
mes.Domain = br.Source.Host.Replace("http", "").Replace("http://", "").Replace("https://", "").Replace("https", "");
mes.Fovicon = $"http://www.google.com/s2/favicons?domain={mes.Domain}";
if (Document != null)
{
var htmls = Document.getElementsByTagName("html");
if (htmls != null && htmls.length > 0)
{
var html = htmls.item(0) as IHTMLElement;
mes.Html = html.outerHTML;
}
}
_pipeClient.PushMessage(mes);
}
catch (Exception ex)
{
throw ex;
}
}
Event Navigating firing, ExecuteInForeground sends messages, but LoadCompleted event is not firing. Could this be due to the settings window - Property = "ResizeMode" Value = "NoResize". What am I doing wrong?

How to report progress on file output using progressbar in WinForms?

I made a program that changes a .txt file by using Writeline(). Everything works fine, just I really want to know whether it is possible or not to show the progress of the writing, or not, and if possible, how. Note: I only recently began with c#.
private void button1_Click(object sender, EventArgs e)
{
string res = "";
{
if (checkBox1.Checked == true) { res = "playercontrols:1:up-w,right-d,left-a,aimy-,run-lshift,reload-r,portal2-,portal1-,jump- ,aimx-,down-s,use-e;playercontrols:2:up-joy-1-hat-1-u,right-joy-1-hat-1-r,left-joy-1-hat-1-l,aimy-joy-1-axe-4-neg,run-joy-1-but-3,reload-joy-1-but-4,portal2-joy-1-but-6,portal1-joy-1-but-5,jump-joy-1-but-1,aimx-joy-1-axe-5-neg,down-joy-1-hat-1-d,use-joy-1-but-2;playercontrols:3:up-joy-2-hat-1-u,right-joy-2-hat-1-r,left-joy-2-hat-1-l,aimy-joy-2-axe-4-neg,run-joy-2-but-3,reload-joy-2-but-4,portal2-joy-2-but-6,portal1-joy-2-but-5,jump-joy-2-but-1,aimx-joy-2-axe-5-neg,down-joy-2-hat-1-d,use-joy-2-but-2;playercontrols:4:up-joy-3-hat-1-u,right-joy-3-hat-1-r,left-joy-3-hat-1-l,aimy-joy-3-axe-4-neg,run-joy-3-but-3,reload-joy-3-but-4,portal2-joy-3-but-6,portal1-joy-3-but-5,jump-joy-3-but-1,aimx-joy-3-axe-5-neg,down-joy-3-hat-1-d,use-joy-3-but-2;playercolors:1:224,32,0,136,112,0,252,152,56;playercolors:2:255,255,255,0,160,0,252,152,56;playercolors:3:0,0,0,200,76,12,252,188,176;playercolors:4:32,56,236,0,128,136,252,152,56;portalhues:1:0,0.125;portalhues:2:0.25,0.375;portalhues:3:0.5,0.625;portalhues:4:0.75,0.875;mariohats:1:1;mariohats:2:1;mariohats:3:1;mariohats:4:1;scale:3;shader1:none;shader2:none;volume:1;mouseowner:1;mappack:smb;gamefinished;"; }
else { res = "playercontrols:1:up-w,right-d,left-a,aimy-,run-lshift,reload-r,portal2-,portal1-,jump- ,aimx-,down-s,use-e;playercontrols:2:up-joy-1-hat-1-u,right-joy-1-hat-1-r,left-joy-1-hat-1-l,aimy-joy-1-axe-4-neg,run-joy-1-but-3,reload-joy-1-but-4,portal2-joy-1-but-6,portal1-joy-1-but-5,jump-joy-1-but-1,aimx-joy-1-axe-5-neg,down-joy-1-hat-1-d,use-joy-1-but-2;playercontrols:3:up-joy-2-hat-1-u,right-joy-2-hat-1-r,left-joy-2-hat-1-l,aimy-joy-2-axe-4-neg,run-joy-2-but-3,reload-joy-2-but-4,portal2-joy-2-but-6,portal1-joy-2-but-5,jump-joy-2-but-1,aimx-joy-2-axe-5-neg,down-joy-2-hat-1-d,use-joy-2-but-2;playercontrols:4:up-joy-3-hat-1-u,right-joy-3-hat-1-r,left-joy-3-hat-1-l,aimy-joy-3-axe-4-neg,run-joy-3-but-3,reload-joy-3-but-4,portal2-joy-3-but-6,portal1-joy-3-but-5,jump-joy-3-but-1,aimx-joy-3-axe-5-neg,down-joy-3-hat-1-d,use-joy-3-but-2;playercolors:1:224,32,0,136,112,0,252,152,56;playercolors:2:255,255,255,0,160,0,252,152,56;playercolors:3:0,0,0,200,76,12,252,188,176;playercolors:4:32,56,236,0,128,136,252,152,56;portalhues:1:0,0.125;portalhues:2:0.25,0.375;portalhues:3:0.5,0.625;portalhues:4:0.75,0.875;mariohats:1:1;mariohats:2:1;mariohats:3:1;mariohats:4:1;scale:3;shader1:none;shader2:none;volume:1;mouseowner:1;mappack:smb;"; }
if (checkBox2.Checked == true) { res = res + "reachedworlds:smb:1,"; }
else { res = res + "reachedworlds:smb:0,"; }
if (checkBox3.Checked == true) { res = res + "1,"; }
else { res = res + "0,"; }
if (checkBox4.Checked == true) { res = res + "1,"; }
else { res = res + "0,"; }
if (checkBox5.Checked == true) { res = res + "1,"; }
else { res = res + "0,"; }
if (checkBox6.Checked == true) { res = res + "1,"; }
else { res = res + "0,"; }
if (checkBox7.Checked == true) { res = res + "1,"; }
else { res = res + "0,"; }
if (checkBox8.Checked == true) { res = res + "1,"; }
else { res = res + "0,"; }
if (checkBox9.Checked == true) { res = res + "1;"; }
else { res = res + "0;"; }
}
DialogResult ans=MessageBox.Show("Warning! All settings in your game will be reset. Do you wish to continue?", "Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
if (ans == DialogResult.OK)
{
string roaming = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string path = roaming + "\\LOVE\\mari0\\options.txt";
using (StreamWriter sr = new StreamWriter(path))
{
sr.Write(res);
}
}
Assuming you're using winforms, based on one of your tags, here's something you can do:
public Form1()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
}
private void WriteToFileMethod()
{
// your routine here
}
private void button_Click(object sender, EventArgs e)
{
progressBar.Maximum = 100;
progressBar.Step = 1;
progressBar.Value = 0;
backgroundWorker.RunWorkerAsync();
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
var backgroundWorker = sender as BackgroundWorker;
for (int i = 0; i < workSize; i++)
{
WriteToFileMethod();
backgroundWorker.ReportProgress((i * 100) / workSize);
}
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
Just replace workSize with the size of the work that you're trying to do. You can also adjust that code to report progress for number of lines that you're writing or number of files. It just depends on what exactly you're trying to report. You can even do memory size.
MSDN does a fantastic job of explaining all the details here. Besides looking at my example, I highly suggest reading up their overview. It'll provide a more detailed understanding of what needs to be done.
Lastly, progress bar might not always be a viable option. Something you can implement to let the user know that a background process is taking place and that the process hasn't crashed is a WaitCursor: Cursor.Current = Cursor.WaitCursor; Just something to think about...

Categories