I have amended my code in App.xaml.cs
But i have an error at "this.ApplicationLifetimeObjects.Add(new XNAAsyncDispatcher(TimeSpan.FromMilliseconds(50)));" (Placed at end of my App.xaml.cs)
The error is
"System.TimeSpan.FromMilliseconds(double) is a method but is used like a type"
System.Windows.Application.ApplicationLifetimeObjects is a property but is used like a type
Identifier expected
Invalid token '(' in a class, struct or interface member declaration
Method must have a return type
Below is the whole piece of my App.xaml.cs
namespace Alarm_Clock
{
public class GlobalData
{
public BitmapImage bitmapImage;
}
public partial class App : Application
{
public static GlobalData globalData;
public class XNAAsyncDispatcher : IApplicationService
{
private readonly DispatcherTimer _frameworkDispatcherTimer;
public XNAAsyncDispatcher(TimeSpan dispatchInterval)
{
_frameworkDispatcherTimer = new DispatcherTimer();
_frameworkDispatcherTimer.Tick += frameworkDispatcherTimer_Tick;
_frameworkDispatcherTimer.Interval = dispatchInterval;
}
void IApplicationService.StartService(ApplicationServiceContext context) { _frameworkDispatcherTimer.Start(); }
void IApplicationService.StopService() { _frameworkDispatcherTimer.Stop(); }
void frameworkDispatcherTimer_Tick(object sender, EventArgs e) { FrameworkDispatcher.Update(); }
}
public static string imagePath
{
//get { return "PhotoNote_{0:yyyy-MM-dd_hh-mm-ss-tt}.jpg"; }
get;
set;
}
/// <summary>
/// Provides easy access to the root frame of the Phone Application.
/// </summary>
/// <returns>The root frame of the Phone Application.</returns>
public PhoneApplicationFrame RootFrame { get; private set; }
//Global variables for the WriteableBitmap objects used throughout the application.
public static WriteableBitmap CapturedImage;
/// <summary>
/// Constructor for the Application object.
/// </summary>
public App()
{
globalData = new GlobalData();
globalData.bitmapImage = new BitmapImage();
// Global handler for uncaught exceptions.
UnhandledException += Application_UnhandledException;
// Show graphics profiling information while debugging.
if (System.Diagnostics.Debugger.IsAttached)
{
// Display the current frame rate counters.
Application.Current.Host.Settings.EnableFrameRateCounter = true;
// Show the areas of the app that are being redrawn in each frame.
//Application.Current.Host.Settings.EnableRedrawRegions = true;
// Enable non-production analysis visualization mode,
// which shows areas of a page that are being GPU accelerated with a colored overlay.
//Application.Current.Host.Settings.EnableCacheVisualization = true;
}
// Standard Silverlight initialization
InitializeComponent();
// Phone-specific initialization
InitializePhoneApplication();
}
// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
}
// Code to execute when the application is activated (brought to foreground)
// This code will not execute when the application is first launched
private void Application_Activated(object sender, ActivatedEventArgs e)
{
}
// Code to execute when the application is deactivated (sent to background)
// This code will not execute when the application is closing
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
}
// Code to execute when the application is closing (eg, user hit Back)
// This code will not execute when the application is deactivated
private void Application_Closing(object sender, ClosingEventArgs e)
{
}
// Code to execute if a navigation fails
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// A navigation has failed; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
// Code to execute on Unhandled Exceptions
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
#region Phone application initialization
// Avoid double-initialization
private bool phoneApplicationInitialized = false;
// Do not add any additional code to this method
private void InitializePhoneApplication()
{
if (phoneApplicationInitialized)
return;
// Create the frame but don't set it as RootVisual yet; this allows the splash
// screen to remain active until the application is ready to render.
RootFrame = new PhoneApplicationFrame();
RootFrame.Navigated += CompleteInitializePhoneApplication;
// Handle navigation failures
RootFrame.NavigationFailed += RootFrame_NavigationFailed;
// Ensure we don't initialize again
phoneApplicationInitialized = true;
}
// Do not add any additional code to this method
private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
{
// Set the root visual to allow the application to render
if (RootVisual != RootFrame)
RootVisual = RootFrame;
// Remove this handler since it is no longer needed
RootFrame.Navigated -= CompleteInitializePhoneApplication;
}
#endregion
this.ApplicationLifetimeObjects.Add(new XNAAsyncDispatcher(TimeSpan.FromMilliseconds(50)));
}
}
The pause just dont work in my code below.
This is my whole piece of code:
namespace Alarm_Clock
{
public partial class AlarmRing : PhoneApplicationPage
{
int songSelectedIndex;
public AlarmRing()
{
InitializeComponent();
SupportedOrientations = SupportedPageOrientation.Portrait;
//Get the DateTime.Now and place it into "timeTxtBlock" text block
timeTxtBlock.Text = DateTime.Now.ToShortTimeString();
//Read from Isolated storage queSetting.txt for the number of question to answer by the user
//Read from Isolated storage music.txt for the selected music to play when the alarm ring
var isoFile = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
try
{
StreamReader readFile = new StreamReader(new IsolatedStorageFileStream("SettingFolder\\music.txt", FileMode.Open, myStore));
songSelectedIndex = Convert.ToInt16(readFile.ReadLine());
readFile.Close();
}
catch (Exception)
{
//If the user did not select the music to be played when the alarm ring it will play the first music by default
songSelectedIndex = 0;
}
using (var ml = new MediaLibrary())
{
//Play the music using media player from the song collection
FrameworkDispatcher.Update();
MediaPlayer.MediaStateChanged += new EventHandler<EventArgs>(MediaPlayer_MediaStateChanged);
MediaPlayer.Play(ml.Songs[songSelectedIndex]);
MediaPlayer.IsRepeating = true;
MediaPlayer.IsMuted = false;
MediaPlayer.IsShuffled = false;
MediaPlayer.IsVisualizationEnabled = false;
}
//Load code
loadtime();
}
static void MediaPlayer_MediaStateChanged(object sender, EventArgs e)
{
if (MediaPlayer.State == MediaState.Paused)
{
MediaPlayer.Resume();
}
}
void loadtime()
{
ringingAlarm.Begin();
//Get the DateTime.Now
String timeNow = DateTime.Now.ToShortTimeString();
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
foreach (string labels in storage.GetFileNames("*"))
{
XElement _xml;
IsolatedStorageFileStream location = new IsolatedStorageFileStream(labels, System.IO.FileMode.Open, storage);
System.IO.StreamReader file = new System.IO.StreamReader(location);
_xml = XElement.Parse(file.ReadToEnd());
if (_xml.Name.LocalName != null)
{
XAttribute time = _xml.Attribute("time");
//Get the day of the week
String dayOfWeek = DateTime.Now.DayOfWeek.ToString("F");
if (timeNow == time.Value.ToString())
{
//"textBlock2" text block will display the label of the alarm
textBlock2.Text = labels;
}
}
file.Dispose();
location.Dispose();
}
}
}
string settingQues;
string settingQuesPassToGame;
string format;
string format1;
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
//Try get the value of number of question to be answered by the user that is pass over from setClockPage.xaml
if (NavigationContext.QueryString.TryGetValue("settingQues", out settingQues))
settingQuesPassToGame = settingQues;
//Try get the format that is passed over
if (NavigationContext.QueryString.TryGetValue("format", out format))
format1 = format;
}
//Display a pop up message box with instruction
//And navigate to "Start.xaml"
private void gameBtn_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("To dismiss alarm" + System.Environment.NewLine + "- Answer selected IQ question" + System.Environment.NewLine + "- With all correct answer");
NavigationService.Navigate(new Uri("/Start.xaml?ringingAlarmTitle=" + textBlock2.Text + "&ringingAlarmTime=" + timeTxtBlock.Text + "&format1=" + format1, UriKind.Relative));
}
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true;
}
public Visibility visible { get; set; }
}
}
When I place MediaPlayer.MediaStateChanged += new EventHandler<EventArgs>(MediaPlayer_MediaStateChanged); at the constructor there is an error.
The error is MediaPlayer.MediaStateChanged += new EventHandler<EventArgs>(MediaPlayer_MediaStateChanged) is a method but is use like a type.
I have changed my code but it still dosent work
static void MediaPlayer_MediaStateChanged(object sender, EventArgs e)
{
if (MediaPlayer.State == MediaState.Paused)
{
MediaPlayer.Resume();
}
}
You have to dispatch XNA Events manual in Windows Phone 7 Apps:
public class XNAAsyncDispatcher : IApplicationService
{
private readonly DispatcherTimer _frameworkDispatcherTimer;
public XNAAsyncDispatcher(TimeSpan dispatchInterval)
{
_frameworkDispatcherTimer = new DispatcherTimer();
_frameworkDispatcherTimer.Tick += frameworkDispatcherTimer_Tick;
_frameworkDispatcherTimer.Interval = dispatchInterval;
}
void IApplicationService.StartService(ApplicationServiceContext context) { _frameworkDispatcherTimer.Start(); }
void IApplicationService.StopService() { _frameworkDispatcherTimer.Stop(); }
void frameworkDispatcherTimer_Tick(object sender, EventArgs e) { FrameworkDispatcher.Update(); }
}
Add this to the end of your public App()
public App()
{
// Other stuff
// End
this.ApplicationLifetimeObjects.Add(new XNAAsyncDispatcher(TimeSpan.FromMilliseconds(50)));
}
Complete Guide: http://msdn.microsoft.com/library/ff842408.aspx
Related
I have class method and event
public class DefaultVariables
{
private DataTable SetDataFromSQL()
{
var Eventstatus = new BasicEventsHandlersArgs();
Eventstatus.Status.Task = BasicEventStatus.Busy;
Eventstatus.Status.Task_Status = "Please wait while we performing";
Eventstatus.Status.Task_CurrentProgress = "Verifying Steps...";
Eventstatus.Status.Task_TotalProgress = "Measuring Source Properties , Destinations Properties and someother(s)";
Raise_DefaultVariablesProgressUpdate(Eventstatus);
// Long running SQLs
}
public event EventHandler<BasicEventsHandlersArgs> Event_DefaultVariablesBasciProgress;
protected virtual void Raise_DefaultVariablesProgressUpdate(BasicEventsHandlersArgs e)
{
Event_DefaultVariablesBasciProgress?.Invoke(this, e);
}
}
and I call it in a Windows Forms app like this:
DefaultVariables variables = new DefaultVariables();
public EmployeeTag(string UserID)
{
InitializeComponent();
variables.Event_DefaultVariablesBasciProgress += Variables_Event_DefaultVariablesBasciProgress;
}
private void Variables_Event_DefaultVariablesBasciProgress(object sender, BasicEventsHandlersArgs e)
{
Application.DoEvents();
LabDepartmentCount.Text = e.Status.Task_Status.ToString();
labDesignationCount.Text = e.Status.Task_CurrentProgress.ToString(); ;
labEmCount.Text = e.Status.Task_TotalProgress.ToString();
// while (e.Status.Task != BasicEventStatus.Completed) { importToolStripMenuItem1.Enabled = false; }
if (e.Status.Task == BasicEventStatus.Busy)
{
importToolStripMenuItem1.Enabled = false;
}
if (e.Status.Task == BasicEventStatus.Completed)
{
importToolStripMenuItem1.Enabled = true;
}
}
private void importToolStripMenuItem1_Click(object sender, EventArgs e)
{
SetDataFromSQL();
}
The code is working and raising event as I expected, no error.
I just want to add button on GUI to pause, stop and continue between execution and want to control SetDataFromSQL, pause if there is long running code inside and continue from there.
Just like backgroundworker.cancel() method.
So how can I pause the execution from GUI button?
How can I pass pause flag to wait until I click continue?
Please help me out
I am handling an event from a child form in its parent form, and when I try adding items from the list contained within the event args of the handler (ScraperForm_SiteScraped in the code below), I am receiving the exception System.InvalidOperationException in my console.
Interestingly enough, it seems to succeed on the first add, but no subsequent attempts.
public partial class ProxyTesterView : UserControl
{
private BindingList<Proxy> proxies = new BindingList<Proxy>();
private BindingList<ProxyJudge> pudges = new BindingList<ProxyJudge>();
private BindingList<ProxyTest> tests = new BindingList<ProxyTest>();
private PauseOrCancelTokenSource pcts = new PauseOrCancelTokenSource();
private ProxyScraperForm scraperForm = new ProxyScraperForm();
public ProxyTesterView()
{
InitializeComponent();
proxies.ListChanged += Proxies_ListChanged;
scraperForm.SiteScraped += ScraperForm_SiteScraped;
}
private void Proxies_ListChanged(object sender, ListChangedEventArgs e)
{
ProxiesDataGridView.RowCount = proxies.Count;
}
private void AddFromScraperToolStripMenuItem_Click(object sender, EventArgs e)
{
scraperForm.Show();
}
private void ScraperForm_SiteScraped(object sender, SiteScrapedEventArgs e)
{
foreach (var proxy in e.ScrapedProxies)
{
proxies.Add(proxy);
}
}
}
Child Form
public partial class ProxyScraperForm : Form
{
private BindingList<IProxyScraperSite> sites = new BindingList<IProxyScraperSite>();
public int ScrapeInterval { get; set; } = 60000;
public event EventHandler<SiteScrapedEventArgs> SiteScraped;
public ProxyScraperForm()
{
InitializeComponent();
sites.Add(new ProxyScraperSiteUsProxyOrg());
sites.Add(new ProxyScraperSiteFreeProxyListNet());
sites.Add(new ProxyScraperSiteFreeProxyListsNet());
sites.Add(new ProxyScraperSiteHideMyName());
sites.Add(new ProxyScraperSiteHidester());
ScraperDataGridView.DataSource = sites;
}
private void ScrapeButton_Click(object sender, EventArgs e)
{
foreach (var site in sites)
{
Task.Run(async () =>
{
while (true)
{
var driver = SeleniumUtility.CreateDefaultFirefoxDriver();
var newProxies = await site.ScrapeAsync(driver);
driver.Quit();
OnSiteScraped(newProxies);
await Task.Delay(5000);
site.Status = $"Waiting {ScrapeInterval / 1000} seconds...";
await Task.Delay(ScrapeInterval);
}
});
}
}
private void OnSiteScraped(List<Proxy> scrapedProxies)
{
if (SiteScraped != null)
{
SiteScraped(this, new SiteScrapedEventArgs(scrapedProxies));
}
}
}
From our comments, turns out that this was a threading issue. As a good practice, always use a try/catch block when there's a chance that an exception can occur in a block of code. :)
Also, if you're using Visual Studio, you can make VS break on more exceptions by pressing CTRL+ALT+E and selecting the checkboxes. You can read more about exception breaking here.
I am a student. This is our first project using two different class files, and it is also only the second one using Forms. So, I don't have much experience with either.
The object is declared and instantiated, but the object is not recognized in any of the subsequent methods. I am following the code on the book. The code on the book declares/instantiates like this:
new Order = new Order( );
I think it needs to be like this, but that still doesn't help the subsequent references:
Order newOrder = new Order( );
This a a complete listing of the driver and the two class files:
Driver:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Diner
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new OrderGUI());
}
}
}
OrderGUI.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Diner
{
public partial class OrderGUI : Form
{
public OrderGUI()
{
InitializeComponent();
}
//For Load - create object
private void OrderGUI_Load(object sender, System.EventArgs e)
{
newOrder = new Order();
for (int i = 0; i < newOrder.menuEntree.Length; i++)
{
this.lstBxEntree.Items.Add(newOrder.menuEntree[i]);
}
}
// Event handler that gets the entree from the
// Listbox and sets the entree price of the Order object.
private void lstBxEntree_SelectedIndexChanged
(object sender, System.EventArgs e)
{
newOrder.Entree = this.lstBxEntree.Text;
}
// Event handler that gets the special request -
// if one is selected from the predefined list.
private void cmboSpecial_SelectedIndexChanged
(object sender, System.EventArgs e)
{
newOrder.SpecialRequest = this.cmboSpecial.Text;
}
// Menu item that displays the order.
private void menuDisplayOrder_Click(object sender,
System.EventArgs e)
{
}
// Event handler that gets the radio button selected and
// sets the drink selection for the Order object
private void Drink_CheckedChanged(object sender,
System.EventArgs e)
{
if (this.radTea.Checked)
newOrder.DrinkSelection = radTea.Text;
else
if (this.radCoffee.Checked)
newOrder.DrinkSelection = radCoffee.Text;
else
if (this.radSoda.Checked)
newOrder.DrinkSelection = radSoda.Text;
else
if (this.radLemon.Checked)
newOrder.DrinkSelection = radLemon.Text;
else
if (this.radJuice.Checked)
newOrder.DrinkSelection = radJuice.Text;
else
if (this.radMilk.Checked)
newOrder.DrinkSelection = radMilk.Text;
}
// Event handler that gets raised when the check box
// for the Water gets clicked.
private void ckBxWater_CheckedChanged
(object sender, System.EventArgs e)
{
if (this.ckBxWater.Checked)
newOrder.WaterSelection = true;
else
newOrder.WaterSelection = false;
}
// Event handler that gets raised when the user types
// values into the text area of the combo box.
private void cmboSpecial_KeyPress
(object sender,
System.Windows.Forms.KeyPressEventArgs e)
{
newOrder.SpecialRequest = this.cmboSpecial.Text;
}
// Event handler that gets raised when the Edit menu
// is clicked to change the entree.
private void menuEditEntree_Click
(object sender, System.EventArgs e)
{
}
// Event handler that gets raised when the Edit menu
// is clicked to change the drink.
private void menuEditDrink_Click
(object sender, System.EventArgs e)
{
}
// Clears selections for all drink radio buttons.
public void ClearDrinks()
{
this.radMilk.Checked = false;
this.radJuice.Checked = false;
this.radSoda.Checked = false;
this.radLemon.Checked = false;
this.radTea.Checked = false;
this.radCoffee.Checked = false;
}
// Clears all selections so that a new order
// can be placed. Resets the Order object back
// to its default values.
private void menuClearOrder_Click
(object sender, System.EventArgs e)
{
}
// Displays the values for the current instance of
// Order object members
private void menuPlaceOrder_Click(object sender,
System.EventArgs e)
{
}
// Event handler that gets raised when the Edit menu
// is clicked to change the special requests.
private void menuEditSpecial_Click(object sender,
System.EventArgs e)
{
}
// Event handler that gets raised when the Help
// menu is clicked to show the About message.
private void menuAbout_Click(object sender,
System.EventArgs e)
{
MessageBox.Show("Student Union -" +
" Diner by the Valley" +
"\n\n\nVersion 1.0");
}
// Event handler that gets raised when the
// Exit is clicked
private void menuExit_Click(object sender,
System.EventArgs e)
{
Application.Exit();
}
}
}
Order.cs:
using System;
using System.Windows.Forms;
namespace Diner
{
public class Order
{
public string[] menuEntree = new
string[] {"Chicken Salad",
"Ham and Cheese",
"Turkey",
"Vegetable Wrap",
"Tuna Salad",
"Avocado and Cheese",
"Club",
"Peanut Butter & Jelly",
"Cheese Toasty",
"Reuben"};
public decimal[] menuEntreePrice = new
decimal[] {4.50m,
5.00m,
4.75m,
4.00m,
4.50m,
4.00m,
5.50m,
3.75m,
3.50m,
5.00m};
private string entree;
private bool waterSelection;
private string drinkSelection;
private string specialRequest;
private decimal entreePrice;
private decimal drinkPrice;
// Default Constructor
public Order()
{
entree = "";
waterSelection = false;
specialRequest = "";
drinkPrice = 0;
entreePrice = 0;
}
//Property for Entree
public string Entree
{
get
{
return entree;
}
set
{
entree = value;
SetEntreePrice();
}
}
// Property for special request
public string SpecialRequest
{
get
{
return specialRequest;
}
set
{
specialRequest = value;
}
}
// Property for Water Selection
public bool WaterSelection
{
set
{
waterSelection = value;
}
}
// Property for Drink Selection
public string DrinkSelection
{
get
{
return drinkSelection;
}
set
{
drinkSelection = value;
SetDrinkPrice();
}
}
// Read-only property for entreee price
public decimal EntreePrice
{
get
{
return entreePrice;
}
}
// Read-only property for drink price
public decimal DrinkPrice
{
get
{
return drinkPrice;
}
}
// After the entree is set, store the entree price
public void SetEntreePrice()
{
for (int i = 0; i < menuEntree.Length; i++)
{
if (menuEntree[i] == entree)
{
entreePrice = menuEntreePrice[i];
}
}
}
// Return the water selection
public string GetWaterSelection()
{
string waterOrNot;
if (waterSelection)
{
waterOrNot = "Water";
}
else
{
waterOrNot = "No Water";
}
return waterOrNot;
}
// After the drink is set, store the drink price
public void SetDrinkPrice()
{
switch (drinkSelection)
{
case "Tea":
case "Coffee":
drinkPrice = 1.50m;
break;
case "Soda":
case "Lemonade":
drinkPrice = 2.00m;
break;
case "Milk":
case "Juice":
drinkPrice = 1.75m;
break;
}
}
// return the total cost of the order
public decimal DetermineTotalCharges()
{
return entreePrice + drinkPrice;
}
public override string ToString()
{
return "Toatal Due: " + DetermineTotalCharges().ToString("C");
}
}
}
I have a C# library, inside which there is a timer that keeps checking a boolean variable ProcessFinished. ProcessFinished is initialized as false.
What I want is that the main application needs to watch the variable Status from the library, and a message box should display once this ProcessFinished becomes true.
The problem I had is the message box never display if I simple execute the main application, but it displays if I step in the main application.
Here is the timer_tick code in main application:
public Window1()
{
_fl = new FijiLauncherControl();
this._statusTimer = new System.Windows.Forms.Timer(); // read log 4 times per sec
this._statusTimer.Interval = 125;
this._statusTimer.Tick += new EventHandler(_statusTimer_Tick);
InitializeComponent();
}
void _statusTimer_Tick(object sender, EventArgs e)
{
try
{
if (_fl.ProcessFinished)
{
System.Windows.MessageBox.Show("Process is finished");
_statusTimer.Stop();
}
}
catch (Exception ex)
{
}
}
private void FijiLaucherButton_Click(object sender, RoutedEventArgs e)
{
_statusTimer.Start();
_fl.LaunchFiji();
}
where the _fl is the object of the class from the other library.
Inside the library, the timer code is like this:
public FijiLauncherControl()
{
_ijmFile = "";
_fijiExeFile = "";
_logFile = "";
_outputDir = "";
_isLogOn = false;
_processOn = false;
_processFinished = false;
_headless = true;
_doneStr = "Procedure is finished.";
_logFileCheckTimer = new System.Timers.Timer(500); // read log 4 times per sec
_logFileCheckTimer.Enabled = true;
_logFileCheckTimer.Elapsed += new System.Timers.ElapsedEventHandler(_logFileCheckTimer_Elapsed);
}
void _logFileCheckTimer_Elapsed(object sender, EventArgs e)
{
if (_processOn && IsLogOn)
{
try
{
_processFinished = CheckStatuts();
}
catch (Exception ex)
{
}
}
}
I am wondering what is going on here? Is there anyway I can see the message box shows up without stepping in? What is the right way to watch ProcessFinished from the main application?
Would it not be better to fire an event from the thread and catch it. Then show the message box?
Like this maybe?
using System;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click( object sender, EventArgs e )
{
var logChecker = new LogChecker();
logChecker.FinishedExvent += () => MessageBox.Show( "Finished" );
logChecker.Start();
}
}
internal class LogChecker
{
public void Start()
{
var thread = new Thread( CheckLog );
thread.Start();
}
private void CheckLog()
{
var progress = 0;
while ( progress < 3000 )
{
Thread.Sleep( 250 );
progress += 250;
}
FinishedExvent();
}
public event TestEventHandler FinishedExvent;
}
internal delegate void TestEventHandler();
}
Try
volatile bool _processFinished;
This is my first post here, but I've using this site regularly to help me with my own app's, and I should say that this site has been a great help to me, so thanks to everyone.
Now my question:
I'm developing my first software app that exchanges data between a sql server and the app itself. It's beeing developed in C#. Saving or retreiving data from the sql server database is no problem.
What I want is a way to inform the user of the delay between the local machine (where the app is installed) and the server. I can make some animations or simply display some text messages. What I need help with is how to create the code that activates/fires/runs when that server communication time is running.
If you can't understand the idea, picture a video game. When it's loading (in some games) you can see the loading screen before the game starts. I need some code that displays that "loading window" when the the app is downloading or uploading data from/to the server.
I would appreciate any code example or web site recommendation.
PS: Sorry for the extensive text, but I want to make sure everyone understand so I don't have to repeat it again :P
How do I implement a progress bar in C#?
How to create a smooth progress bar in Visual C#
ProgressBar Class
I have developed a simple PleaseWait class 2 years ago, but I didn't update this class, It works very well, have look hope this will give you an idea to implement your logic.
public partial class frmWait : Form
{
public frmWait()
{
InitializeComponent();
}
bool _isMoving = false;
int _moveStart_x = 0;
int _moveStart_y = 0;
private void tmrProgress_Tick(object sender, EventArgs e)
{
if (barProgress.Value == barProgress.Maximum)
barProgress.Value = barProgress.Minimum;
else
barProgress.Value += 1;
}
private void btnCancel_Click(object sender, EventArgs e)
{
Close();
PleaseWait.Abort();
}
protected override CreateParams CreateParams
{
get
{
System.Windows.Forms.CreateParams p = base.CreateParams;
p.ClassStyle += 0x20000;
p.ExStyle += 0x8000000;
return p;
}
}
protected override void WndProc(ref Message m)
{
const int WM_NCHITTEST = 132;
base.WndProc(ref m);
switch (m.Msg)
{
case WM_NCHITTEST:
if (m.Result.ToInt32() == 1)
m.Result = new IntPtr(2);
break;
}
}
private void panelEx1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
_isMoving = true;
_moveStart_x = e.X;
_moveStart_y = e.Y;
}
}
private void panelEx1_MouseUp(object sender, MouseEventArgs e)
{
_isMoving = false;
}
private void pnlContainer_MouseMove(object sender, MouseEventArgs e)
{
if (_isMoving)
this.Location = new Point(Location.X + e.X - _moveStart_x, Location.Y + e.Y - _moveStart_y);
}
}
public class PleaseWait
{
#region Static Operations
private static Boolean _isAborted = false;
private static Boolean _isVisible = false;
private static frmWait _waitForm;
private static String _waitingState = "";
private static Boolean _autoClose = false;
private static Boolean _cancelable = false;
private static System.Threading.Thread _waiterThred;
public delegate void CancelButtonPressed();
public static event CancelButtonPressed OnCancel;
public static Boolean AutoClose
{
get { return PleaseWait._autoClose; }
set { PleaseWait._autoClose = value; }
}
public static string WaitingState
{
get { return PleaseWait._waitingState; }
set { PleaseWait._waitingState = value; }
}
public static bool IsVisible
{
get { return _isVisible; }
internal set { _isVisible = value; }
}
public static void ShowPleaseWait()
{
ShowPleaseWait("", _autoClose, false);
}
public static void ShowPleaseWait(string waitingState)
{
ShowPleaseWait(waitingState, _autoClose, false);
}
public static void ShowPleaseWait(bool autoClose)
{
ShowPleaseWait("", autoClose, false);
}
public static void ShowPleaseWait(string waitingState, bool autoClose, bool cancelable)
{
if (_waiterThred != null)
{
if (_isVisible)
{
// the please wait it woking, just continue and apply the changes
_waitingState = waitingState;
_autoClose = autoClose;
_cancelable = cancelable;
return;
}
else
{
_waiterThred.Abort();
_waiterThred = null;
}
}
_waitingState = waitingState;
_autoClose = autoClose;
_cancelable = cancelable;
_isAborted = false;
_isVisible = false;
if (_autoClose)
Application.Idle += new EventHandler(Application_Idle);
_waiterThred = new System.Threading.Thread(DisplayWaitingForm);
_waiterThred.IsBackground = true;
_waiterThred.Name = "Please Wait....";
_waiterThred.Start();
Application.DoEvents();
}
public static void Abort()
{
_isAborted = true;
}
private static void Application_Idle(object sender, EventArgs e)
{
if (_autoClose)
_isAborted = true;
}
private static void DisplayWaitingForm()
{
if (_waitForm != null)
{
if (!_waitForm.IsDisposed)
_waitForm.Dispose();
_waitForm = null;
_isVisible = false;
}
try
{
if (_isAborted)
return;
_waitForm = new frmWait();
if (_cancelable)
{
_waitForm.btnCancel.Enabled = true;
_waitForm.btnCancel.Click += new EventHandler(btnCancel_Click);
}
try
{
_isVisible = true;
_waitForm.Show();
_waitForm.Focus();
while (!_isAborted)
{
System.Threading.Thread.Sleep(15);
_waitForm.lblMessage.Text = _waitingState;
Application.DoEvents();
_waitForm.lblMessage.Text = _waitingState;
}
_isVisible = false;
}
finally
{
FreeWaitingForm();
}
}
finally
{
_isVisible = false;
}
}
static void btnCancel_Click(object sender, EventArgs e)
{
if (_waitForm.InvokeRequired)
{
_waitForm.BeginInvoke(new EventHandler(btnCancel_Click), new object[] { e });
}
else
{
if (OnCancel != null)
OnCancel.Invoke();
}
}
private static void FreeWaitingForm()
{
_waitingState = "";
_isVisible = false;
if (_waitForm == null)
{
return;
}
_waitForm.Hide();
if (!_waitForm.IsDisposed)
_waitForm.Dispose();
_waitForm = null;
}
#endregion
}
use like following code :
PleaseWait.ShowPleaseWait("Please wait", true, false);
// If second param is true then it will close the form automatically.
// If third param is true the it will expose a cancel button, so you can cancel your Asynchronous operations.
I didn't insert design code, you can understand by looking at code.
hope this help.
First let me thank you for your replies.
Toby your answer got me thinking about thread monitoring my sql connections but it was a bit tricky and confusing since the app is still in develop and will use a lot more connections.
S.Amani answer it wasn't quite what I want, but thanks to that I found a easier way. I created a form (could be anything else), placed a label saying: Saving To Data Base, took out the top bar, defined location and defined it's parent to be disabled when shown and enabled when closed. The following code is what I put inside my DataBaseInteractionClass
private Wait myCustomWaitDialog = new Wait(); // My Waiting form
private void SaveToDatabase(myObjectToSave obj) // Method called to save data do DB
{
// Create the connections and queries
(...)
// This is what I did
// Show Waiting Form
myCustomWaitDialog.Show();
// Instanciate the command that will carry the query and to DB
SqlCommand command = new SqlCommand(Queries.GetData(code), conn);
// This is important
//Create event that will fire when the command completes
command.StatementCompleted += new StatementCompletedEventHandler(command_StatementCompleted);
// Execute the transaction
SqlDataReader reader = command.ExecuteReader();
// Rest of the code (validations, close connections, try/catch, etc
(...)
}
void command_StatementCompleted(object sender, StatementCompletedEventArgs e)
{
// This is the method that closes my Waiting Dialog
myCustomWaitDialog.CloseDialog();
myCustomWaitDialog.Dispose();
}
It's not quite what I want yet, but is the best solution that I found so far. For now it will do :)
Anyway, thanks for the replies and I hope this helps someone else.