C# brief delay after clicking image to display new source - c#

I've got an Windows.Controls.Image that when clicked needs to change its source and have that displayed for x milliseconds before then navigating to a new Page. I tried using Thread.Sleep(200) after changing the source but no matter how I tried to force a redraw the changed source was not displayed and then when the sleep was over it instantly changed page. Does anyone know how I can do this? Cheers!
private void ButtonClicked(object sender, MouseButtonEventArgs e)
{
Image button = (Image)sender;
buttons[button.Name].Source = ImageResizer.ResizeImage(System.Drawing.Image.FromFile(#"D:\buttons\" + button.Name + ".png"), buttonSize);
NavigationService.Navigate(new UpgradeQuiz());
}

You can asynchronously wait:
await Task.Delay(2000);
But you should make your handler async:
private async void ButtonClicked(object sender, MouseButtonEventArgs e) // async after private
{
Image button = (Image)sender;
buttons[button.Name].Source = ImageResizer.ResizeImage(System.Drawing.Image.FromFile(#"D:\buttons\" + button.Name + ".png"), buttonSize);
await Task.Delay(2000);
NavigationService.Navigate(new UpgradeQuiz());
}

Related

WebBrowser.DocumentCompleted and Navigate - C#

I'm trying to modify a simple application which use the WebBrowser item:
private void button1_Click(object sender, EventArgs e)
{
var menu = webBrowser1.Document.GetElementById("SomeItem").InvokeMember("click");
webBrowser1.Visible = true;
button1.Visible = false;
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.Visible = false;
webBrowser1.AllowNavigation = true;
webBrowser1.Navigate("domain");
}
This works fine, the page load and then after clicking the button the user is redirected to the desired location.
Now I'm trying to make this without the help of the button.
Simply put the button code inside the load function didn't help, so I've introduced in my code the DocumentCompleted event.
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.AllowNavigation = true;
webBrowser1.Navigate("SomeDomain");
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentComplete);
}
private void wb_DocumentComplete(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser wb = sender as WebBrowser;
wb.Document.GetElementById("SomeItem").InvokeMember("click");
}
By debugging it, I saw that the wb object is correctly instantiated with the "domain" but I got System.NullReferenceException when I try to retrieve SomeItem.
The document is not fully loaded because I'm still in the load function ?

sound not playing at the right moment

I created a MediaElement for a Background Music in my Windows Phone App and it plays perfectly
now the problem when I tried to add sound for a button when pressed
When I debug , the Background music plays , but when I press the button it navigates me to the next page without playing the sound I created, and when I press BackButton from the Navigated Page, it plays it, why?
code:
private void play_Click(object sender, RoutedEventArgs e)
{
MediaElement Click = new MediaElement();
Click.Source = new Uri ("/Assets/Sounds/press.mp3",UriKind.Relative);
Click.Position = TimeSpan.Zero;
Click.Volume = 1;
LayoutRoot.Children.Add(Click);
Click.Play();
NavigationService.Navigate(new Uri("/NavPage.xaml", UriKind.Relative));
}
private void play_Click(object sender, RoutedEventArgs e)
{
MediaElement Click = new MediaElement();
Click.Source = new Uri ("/Assets/Sounds/press.mp3",UriKind.Relative);
Click.Position = TimeSpan.Zero;
Click.Volume = 1;
LayoutRoot.Children.Add(Click);
Click.Play();
}
you should handle this outside button click,
NavigationService.Navigate(new Uri("/NavPage.xaml", UriKind.Relative));
Add an event handler to the click and call separately,
Click.MediaEnded += Click_Completed;
void Click_Completed(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/NavPage.xaml", UriKind.Relative));
}
or you can make MediaEnded event of the mediaElement and there in you can call the navigation
Like this:
private void play_Click(object sender, RoutedEventArgs e)
{
MediaElement Click = new MediaElement();
Click.Source = new Uri ("/Assets/Sounds/press.mp3",UriKind.Relative);
Click.Position = TimeSpan.Zero;
Click.Volume = 1;
LayoutRoot.Children.Add(Click);
Click.MediaEnded += Click_MediaEnded;
Click.Play();
}
void Click_MediaEnded(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/NavPage.xaml", UriKind.Relative));
}

How to use WebBrowser in windows phone?

I'm using the following code to make my app to load a url,
WebBrowser wb = new WebBrowser();
wb.Navigate(new Uri(uri,UriKind.Absolute));
But still it is not loading that page? What could be the problem??
WebBrowser is a control. Like a button or a textblock, you won't see anything unless you put it somewhere in your page.
To launch an external browser, use WebBrowserTask:
var webBrowserTask = new WebBrowserTask();
webBrowserTask.Uri = new Uri(uri, UriKind.Absolute);
webBrowserTask.Show();
Yo can't have any callbacks with the default WebBrowserTask in wp, if you need more control, use the WebBrowser as you have been doing,
Xaml
<phone:WebBrowser IsScriptEnabled="True" LoadCompleted="UriContentLoaded" x:Name="browserControl" />
Code Behind
public MainPage() //Your page constructor
{
InitializeComponent();
this.browserControl.Loaded += SetBrowserUri;
}
private void SetBrowserUri(object sender, RoutedEventArgs e)
{
browserControl.Navigate(new Uri("http://www.bing.com"));
}
private void UriContentLoaded(object sender, NavigationEventArgs e)
{
if (MessageBox.Show("Do you want to load a second uri?", "Load again", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
{
browserControl.LoadCompleted -= this.UriContentLoaded; //Remove previous handler
browserControl.LoadCompleted += this.SecondUriContentLoaded; //Add new handler
browserControl.Navigate(new Uri("http://www.google.com"));
}
}
private void SecondUriContentLoaded(object sender, NavigationEventArgs e)
{
MessageBox.Show("Finished loading");
}

Source code to text file not working using C#.net and Web browser?

This source code scraping is not working; it's giving a blank text file as output:
private void button2_Click(object sender, EventArgs e)
{
webBrowser1.Navigate("https://www.jigsaw.com/SearchCompany.xhtml?opCode=refresh&rpage=20&order=0&orderby=0&industry=1160000&subindustry=1160300&country=9000&country=2000&cmDead=false&count=0&screenNameType=0&screenName=&omitScreenNameType=0&omitScreenName=&rowsPerPage=200&uid=13473859&tok=1354716874406-8761960955252771794");
string MainsourceCode = webBrowser1.DocumentText;
StreamWriter sw = new StreamWriter("G:/jigsaw_info.txt", true);
sw.Write(MainsourceCode + "\n");
sw.Close();
}
You are starting to write too fast. You should wait DocumentCompleted event.
private void button2_Click(object sender, EventArgs e)
{
webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
webBrowser1.Navigate("https://www.jigsaw.com/SearchCompany.xhtml?opCode=refresh&rpage=20&order=0&orderby=0&industry=1160000&subindustry=1160300&country=9000&country=2000&cmDead=false&count=0&screenNameType=0&screenName=&omitScreenNameType=0&omitScreenName=&rowsPerPage=200&uid=13473859&tok=1354716874406-8761960955252771794");
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
File.WriteAllText("G:/jigsaw_info.txt",webBrowser1.DocumentText);
}
You have to wait until navigation is complete. Navigation is asynchronous.
Detect WebBrowser complete page loading

show loading or progress bar in c# winforms

I have windows application in which i need to save data into database and after saving data load crystal report to show report,all this happens on click of save button.
I have button named btn_Submit on click of this data is saved and display report, while saving it takes time so i want to show progress bar for mean time so that user get known that data is in process.how i can do with this windows application.
I gone through this link http://www.codeproject.com/Tips/83317/BackgroundWorker-and-ProgressBar-demo but don't get it exactly I want.
I am aware of background worker but never used it.
I have used background worker and progress bar as given in above link but progress bar does not stop at all once it started.
Can any one help me?can u give any example or link that demonstrate scenario?.
This code i added on Dowork();
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
PrintData arg = (PrintData)e.Argument;
SalesMaster sm = arg.SalesData;
BrokerMaster bm = arg.Broker;
CustomerMaster ctm = arg.Customer;
CompanyMaster cm = arg.Company;
ArrayList hb = arg.Arrardata;
int totunit = arg.totunit;
decimal globalamt = arg.golbamt;
SalesReport sreport = new SalesReport(sm, ctm, cm, bm, hb, totunit, glb_totalamt);
sreport .MdiParent = arg.parentf;
sreport .WindowState = FormWindowState.Maximized;
sreport .Show();
}
i get error on this line sreport .MdiParent = arg.parentf;
This error:
Cross-thread operation not valid: Control 'frmParent' accessed from a thread other than the thread it was created on.
what should be done here?
Suscribe to DoWork and RunWorkerCompleted events and
void btn_Submit_Click(object sender, EventArgs e)
{
btn_Submit.Enabled = false; // disable button while saving report
lbl_Status.Text = "Please wait..";
backgroundWorker.RunWorkerAsync();
}
void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
// save report here
}
void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
btn_Submit.Enabled = true; // enable button
lbl_Status.Text = "Report saved";
}
Instead of using label, you can show PictureBox with spinner wait image. I don't like to see progress bar, which does not show percentage of task - I expect that when progress bar will be filled, task will be completed. If you really want to use progress bar, then, I'd go with timer component (set timer's interval to desired refresh rate):
void btn_Submit_Click(object sender, EventArgs e)
{
btn_Submit.Enabled = false; // disable button while saving report
timer.Start();
progressBar.Visible = true;
// backgroundWorker.RunWorkerAsync(new object[] { "Foo", 42 });
// backgroundWorker.RunWorkerAsync(new CustomType("Foo", 42));
backgroundWorker.RunWorkerAsync(new { Foo = "Foo", Bar = 42 }););
}
void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
// object[] args = (object[])e.Argument;
// CustomType arg = (CustomType)e.Argument;
dynamic arg = (dynamic)e.Argument;
string foo = arg.Foo;
int bar = arg.Bar;
// save report here
}
void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
btn_Submit.Enabled = true; // enable button
timer.Stop();
progressBar.Visible = false;
}
void timer_Tick(object sender, EventArgs e)
{
if (progressBar.Value == progressBar.Maximum)
{
progressBar.Value = progressBar.Minimum;
return;
}
progressBar.PerformStep();
}
Try to reset the ProgressBar's Value property to 0, like in the code below:
Worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Worker_RunWorkerCompleted);
Implemented event handler:
void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
progressBar1.Value = 0;
}
To stop or hide the progressbar use background worker's completed event.

Categories