private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (listBox1.Items.Contains(e.KeyCode))
{
listBox1.Items.Remove(e.KeyCode);
listBox1.Refresh();
timer1.Interval -= 10;
difficultyProgessbar.Value = 800 - timer1.Interval;
stats.update(true);
}
else
{
stats.update(false);
}
correctLabel.Text = stats.correct.ToString();
missedLabel.Text = stats.missed.ToString();
totalLabel.Text = stats.total.ToString();
accuracyLabel.Text = stats.accuracy.ToString();
}
private void timer1_Tick(object sender, EventArgs e)
{
//Add a random key to Listbox
listBox1.Items.Add((Keys)random.Next(65, 90));
Application.DoEvents();
if (listBox1.Items.Count > 7)
{
listBox1.Items.Clear();
listBox1.Items.Add("Game Over");
timer1.Stop();
}
}
When I run my application, timer1_Tick event is working fine, however Form1_KeyDown event doesn't execute when I press any key.
Is something missing? Why Key_Down event never fires?
Thanks
Keydown fires in the Control with Focus.
To receive it at the Form level you need to set the property. KeyPreview=True for the Form
Related
I am using a C# webBrowser control using the DocumentCompleted -
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
I am then navigating -
webBrowser1.Navigate("myUrl")
However if the request to that server hangs, i.e. the page does not complete after say 10 seconds, how could I implement the webBrowser1.Stop();?
I did try to implement a count, that if it got to 20 i.e. the webBrowser1_DocumentCompleted went into an infinite loop (the page would not complete) then stop however not sure if this is the most straightforward way of doing htis?
This might be in really bad practice so I apologize but you could use a boolean control with a timer to check whether or not the document has completed and if it hasn't, close the webBrowser.
First of all add a timer(assuming its called Timer1) to your form, setting interval to 1000 and create an int and bool control.
int timeLeft;
bool hasCompleted = false;
Run your URL as normal and start your timer
webBrowser1.Navigate("myUrl");
timeLeft = 10;
Timer1.Start();
And your timer should look like this;
private void timer1_Tick(object sender, EventArgs e)
{
if(timeLeft > 0) {
timeLeft = timeLeft - 1;
}
if(timeLeft = 0 && !hasCompleted)
{
timer1.Stop();
webBrowser1.Stop();
}
else{
timer1.Stop();
}
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
hasCompleted = true;
//your code
}
I have tried to achieve this using the timer.
I just added a timer and set the interval.
Here is the code
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timer1.Tick += timer1_Tick;
webBrowser1.DocumentCompleted += new
WebBrowserDocumentCompletedEventHandler( webBrowser1_DocumentCompleted);
LoadBrowser();
}
void timer1_Tick(object sender, EventArgs e)
{
timer1.Enabled = false;
webBrowser1.DocumentText = "Cancelled";
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (timer1.Enabled)
{
MessageBox.Show("Page Loaded succesfully");
}
}
private void LoadBrowser()
{
timer1.Enabled = true;
webBrowser1.Url = new Uri("http://www.microsoft.com");
}
}
I create following form and I click 3 buttons (randomly). After I click a button, it must show a related message after 3 seconds from clicking it. But if I had clicked another button in the meanwhile, then the related message of that button has to be shown and the previous message in the queue has to be canceled.
As an example, if I click button1 at 11.30.00, then related message should pop up only at 11.30.03 like "You clicked : 1 before 3 Seconds". But if I click another button2 before the 11.30.03, say at 11.30.02 then related message should pop up at 11.30.05 like "You clicked : 2 before 3 Seconds" and the message scheduled for 11.30.03 has to be canceled.
This is my code:
private int signal = 0;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
signal = 1;
displayMessage(signal);
}
private void button2_Click(object sender, EventArgs e)
{
signal = 2;
displayMessage(signal);
}
private void button3_Click(object sender, EventArgs e)
{
signal = 3;
displayMessage(signal);
}
private void displayMessage(int number)
{
MessageBox.Show("You clicked : "+number+ "before 3 Seconds");
}
Set buttons Tag:
button1.Tag = 1;
button2.Tag = 2;
button3.Tag = 3;
then set Click event:
button1.Click += button_Click;
button2.Click += button_Click;
button3.Click += button_Click;
on the Click event:
private void button_Click(object sender, EventArgs e)
{
signal = (int) ((Button))sender.Tag;
displayMessage(signal);
}
Start a timer. Keep changing signal value according to button click, and when time elapsed is equal to 3 seconds, show up the messagebox from tick event. Set the timer interval according to your need and that will be reflected in the "related message".
int signal = 0;
System.Timers.Timer t = new System.Timers.Timer(3000);
private void Form1_Load(object sender, EventArgs e)
{
//----------------------- other parts of code ---------------------
// at last
t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed);
t.Start();
}
void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (signal == 0)
return;
t.Stop();
MessageBox.Show("You clicked: " + signal + " before " + t.Interval + " Seconds");
signal = 0;
t.Start(); //move this to top of msgbox if you want timer to be reset right after poppin the msgbox.
}
private void button1_Click(object sender, EventArgs e)
{
signal = 1;
t.Stop();
t.Start();
}
private void button2_Click(object sender, EventArgs e)
{
signal = 2;
t.Stop();
t.Start();
}
private void button3_Click(object sender, EventArgs e)
{
signal = 3;
t.Stop();
t.Start();
}
This isn't a place where someone is just going to give you an answer, do some research into the area then post if you get stuck.
you want to create a static timer and check if its finished within each event
http://msdn.microsoft.com/en-us/library/79b3xss3(v=vs.80).aspx
http://msdn.microsoft.com/en-us/library/system.timers.timer(v=vs.71).aspx
ok i have question, i made this code to play axmediaplayer base on item listed on listbox.
first i make this code to make a list using opendialog :
private string[] files, path;
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
files = openFileDialog1.SafeFileNames;
path = openFileDialog1.FileNames;
for (int i = 0; i < files.Length; i++) {
listBox1.Items.Add(files[i]);
}
}
}
and then it play the music when the listbox index changed (when the item on the list box cliked) using this code :
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
axWindowsMediaPlayer1.URL = path[listBox1.SelectedIndex];
}
it works fine, and then i want player to automove to the next song base on item on my listbox. with using events PlayStateChange, so i make this code
private void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if (axWindowsMediaPlayer1.playState == WMPLib.WMPPlayState.wmppsMediaEnded)
{
if(listBox1.SelectedIndex < files.Length - 1)
{
listBox1.SelectedIndex = listBox1.SelectedIndex + 1;
}
}
}
the selected index change, but the player doesn't auto play the next song. i must click the play button manually in order to play the list. can anyone help me up?
ok i found it, the solution is to add timer before playing the next song.
first im adding timer, that shoud be timer1. and then i change playstate event to something like this :
private void axWindowsMediaPlayer1_PlayStateChange(object sender, axWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if (axWindowsMediaPlayer1.playState == WMPLib.WMPPlayState.wmppsMediaEnded)
{
timer1.Interval = 100;
timer1.Enabled = true;
}
}
then on the timer i adding tick event, the tick event is something like this :
private void timer1_Tick(object sender, EventArgs e)
{
if (listBox1.SelectedIndex < files.Length - 1)
{
listBox1.SelectedIndex++;
timer1.Enabled = false;
}
else
{
listBox1.SelectedIndex = 0;
timer1.Enabled = false;
}
}
now its work fine ^^
Below functionality worked for me:
private void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if ((WMPLib.WMPPlayState)e.newState == WMPLib.WMPPlayState.wmppsMediaEnded)
{
timer1.Interval = 100;
timer1.Start();
timer1.Enabled = true;
timer1.Tick += timer1_Tick;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
/// method to play video list items
myFuntiontoPlayVideo();
timer1.Enabled = false;
}
I have a listbox1 which is bound to a DataTable named Notes, the line on which I set value in cell of DataTable changes listBox1.SelectedIndex = -1 then again set listBox1.SelectedIndex to original value and finishes. Hence that line calls listBox1_SelectedIndexChanged event twice.
Instead it should not even call that event. How to solve this problem?
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
dataSet11.Notes.Rows[listBox1.SelectedIndex]["Text"] = richTextBox1.Text;
//this line fires listBox1_SelectedIndexChanged event
//with listBox1.SelectedIndex = -1
//then it changes listBox1.SelectedIndex back to original value before complete execution, and calls the even again
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
Temporarily remove the SelectedIndexChanged handlers
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
listBox1.SelectedIndexChanged -= listBox1_SelectedIndexChanged;
if (listBox1.SelectedIndex != -1)
{
dataSet11.Notes.Rows[listBox1.SelectedIndex]["Text"] = richTextBox1.Text;
//this line fires listBox1_SelectedIndexChanged event
//with listBox1.SelectedIndex = -1
//then it changes listBox1.SelectedIndex back to original value before complete execution, and calls the even again
}
listBox1.SelectedIndexChanged += listBox1_SelectedIndexChanged;
}
You can use a trigger boolean field for this:
private TextBox_OntextChanged(object sender, EventArgs args)
{
this.supressEvents = true;
//Do your stuff here
this.supressEvents = false;
}
private void ListBox_OnSelectionChanged(object sender, EventArgs args)
{
if (this.supressEvents)
{
return;
}
//Do your stuff here
}
I can catch a single-click on a TextBlock like this:
private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)
{
MessageBox.Show("you single-clicked");
}
I can catch a double-click on a TextBlock like this:
private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
if (e.ClickCount == 2)
{
MessageBox.Show("you double-clicked");
}
}
}
But how do I catch them both on a single TextBlock and differentiate between the two?
You need to fire the event after the click sequence is over... when is that? I suggest using a timer. The MouseDown event would reset it and increase the click count. When timer interval elapses it makes the call to evaluate the click count.
private System.Timers.Timer ClickTimer;
private int ClickCounter;
public MyView()
{
ClickTimer = new Timer(300);
ClickTimer.Elapsed += new ElapsedEventHandler(EvaluateClicks);
InitializeComponent();
}
private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)
{
ClickTimer.Stop();
ClickCounter++;
ClickTimer.Start();
}
private void EvaluateClicks(object source, ElapsedEventArgs e)
{
ClickTimer.Stop();
// Evaluate ClickCounter here
ClickCounter = 0;
}
Cheers!
If you need to detect the difference, I suggest you use a control such as Label that does the work for you:
label.MouseDown += delegate(object sender, MouseEventArgs e)
{
if (e.ClickCount == 1)
{
// single click
}
};
label.MouseDoubleClick += delegate
{
// double click
};
EDIT: My advice was following from documentation on MSDN:
The Control class defines the
PreviewMouseDoubleClick and
MouseDoubleClick events, but not
corresponding single-click events. To
see if the user has clicked the
control once, handle the MouseDown
event (or one of its counterparts) and
check whether the ClickCount property
value is 1.
However, doing so will give you a single click notification even if the user single clicks.
You must use a timer to differentiate between the two. Add a timer to your form in the GUI (easiest that way - it will automatically handle disposing etc...). In my example, the timer is called clickTimer.
private bool mSingleClick;
private void TextBlock_MouseUp(object sender, MouseButtonEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
if (e.ClickCount < 2)
{
mSingleClick = true;
clickTimer.Interval = System.Windows.Forms.SystemInformation.DoubleClickTime;
clickTimer.Start();
}
else if (e.ClickCount == 2)
{
clickTimer.Stop();
mSingleClick = false;
MessageBox.Show("you double-clicked");
}
}
}
private void clickTimer_Tick(object sender, EventArgs e)
{
if (mSingleClick)
{
clickTimer.Stop();
mSingleClick = false;
MessageBox.Show("you single-clicked");
}
}
I did it this Way and it works perfectly
If e.Clicks = 2 Then
doubleClickTimer.Stop()
ElseIf e.Clicks = 1 Then
doubleClickTimer.Enabled = True
doubleClickTimer.Interval = 1000
doubleClickTimer.Start()
End If
Private Sub doubleClickTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles doubleClickTimer.Tick
OpenWebPage("abc")
doubleClickTimer.Stop()
End Sub
You are simply can use MouseDown event and count click number, like this:
if (e.ChangedButton == MouseButton.Left && e.ClickCount == 2)
{
// your code here
}
My suggestion, implemented in a UserControl by simply using a Task:
private int _clickCount = 0;
protected override void OnPreviewMouseDown(MouseButtonEventArgs e)
{
_clickCount = e.ClickCount;
}
protected override async void OnPreviewMouseUp(MouseButtonEventArgs e)
{
if (_clickCount > 1)
{
//apparently a second mouse down event has fired => this must be the second mouse up event
//no need to start another task
//the first mouse up event will be handled after the task below
return;
}
await Task.Delay(500);
if (_clickCount == 1)
{
//single click
}
else
{
//double (or more) click
}
}
The drawback of all these solutions is, of course, that there will be a delay before actually responding to the user's action.
You could do it on MouseUp instead of MouseDown. That way you can ask the ClickCount property for the total number of clicks, and decide what to do from that point.
It's my working solution :)
#region message label click --------------------------------------------------------------------------
private Timer messageLabelClickTimer = null;
private void messageLabel_MouseUp(object sender, MouseButtonEventArgs e)
{
Debug.Print(e.ChangedButton.ToString() + " / Left:" + e.LeftButton.ToString() + " Right:" + e.RightButton.ToString() + " click: " + e.ClickCount.ToString());
// in MouseUp (e.ClickCount == 2) don't work!! Always 1 comes.
// in MouseDown is set e.ClickCount succesfully (but I don't know should I fire one clicked event or wait second click)
if (e.ChangedButton == MouseButton.Left)
{
if (messageLabelClickTimer == null)
{
messageLabelClickTimer = new Timer();
messageLabelClickTimer.Interval = 300;
messageLabelClickTimer.Elapsed += new ElapsedEventHandler(messageLabelClickTimer_Tick);
}
if (! messageLabelClickTimer.Enabled)
{ // Equal: (e.ClickCount == 1)
messageLabelClickTimer.Start();
}
else
{ // Equal: (e.ClickCount == 2)
messageLabelClickTimer.Stop();
var player = new SoundPlayer(ExtraResource.bip_3short); // Double clicked signal
player.Play();
}
}
}
private void messageLabelClickTimer_Tick(object sender, EventArgs e)
{ // single-clicked
messageLabelClickTimer.Stop();
var player = new SoundPlayer(ExtraResource.bip_1short); // Single clicked signal
player.Play();
}
#endregion
My issue was with single/double-clicking rows in a DataGrid in WPF. For some reason the ButtonDown events weren't firing, only the OnMouseLeftButtonUp event was. Anyway, I wanted to handle the single-click differently from the double-click. It looks me a little time (I'm sure the solution isn't perfect, but it appears to work) to distill the problem down until I got it down to the below. I created a Task which calls an Action and that Action's target can be updated by a second click. Hope this helps someone!
private Action _clickAction;
private int _clickCount;
private void Grid_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
Debug.WriteLine("Button Click Occurred");
_clickCount++;
if (_clickCount == 1)
{
_clickAction = SingleClick;
}
if (_clickCount > 1)
{
_clickAction = DoubleClick;
}
if (_clickCount == 1)
{
Task.Delay(200)
.ContinueWith(t => _clickAction(), TaskScheduler.FromCurrentSynchronizationContext())
.ContinueWith(t => { _clickCount = 0; });
}
}
private void DoubleGridClick()
{
Debug.WriteLine("Double Click");
}
private void SingleGridClick()
{
Debug.WriteLine("Single Click");
}