I want to check the mouse leave of tab area of TabPage. but its not working properly. sometimes I get the messagebox sometimes not.
TabPage mouseTab = null;
void tabControl1_MouseMove(object sender, MouseEventArgs e) {
TabPage checkTab = null;
for (int i = 0; i < tabControl1.TabPages.Count; ++i) {
if (tabControl1.GetTabRect(i).Contains(e.Location)) {
checkTab = tabControl1.TabPages[i];
}
}
if (checkTab == null && mouseTab != null) {
mouseTab = null;
MessageBox.Show("MouseLeave");
} else if (checkTab != null) {
if (mouseTab == null || !checkTab.Equals(mouseTab)) {
mouseTab = checkTab;
}
}
}
Related
In C#, I cannot get DataGridViewCheckBoxColumn event to work. It always get a FALSE value even though I’ve clicked on the checkbox. The other datagridviews (text and combobox) columns work fine. Here is what I am doing…
OK, so I am dynamically creating datagridviews (DGVs) at runtime in my constructor based on how many tab sheets there are in the tab control which is determined by the number of weeks in any given date range i.e. one DGV per tab page (where you tab page for each week)
for (int i = 0; i < wcNumWeeks; i++)
{
foreach (DataRow dr in wbDatesDT.Rows)
{
if (Convert.ToInt16(dr["tabNo"].ToString()) == i + 1)
{
wcDate = Convert.ToDateTime(dr["wcDate"].ToString());
break;
}
}
weeksTabControl.TabPages.Add(wcDate.ToShortDateString());
weeksTabControl.TabPages[i].AutoScroll = true;
weeksTabControl.TabPages[i].Width = 1500;
weeksTabControl.TabPages[i].Height = 700;
weeksTabControl.TabPages[i].Controls.Add(new DataGridView()
{
Name = "dataGridView" + (i + 1).ToString(),
Dock = DockStyle.Fill,
Width = 1450,
Height = 650,
Anchor = (AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right),
ScrollBars = System.Windows.Forms.ScrollBars.Both,
AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
});
}
Again in the constructor, for each datagridview created I am creating event as follows:
foreach (Control thisControl in weeksTabControl.Controls)
{
if (thisControl.GetType() == typeof(TabPage))
{
foreach (Control dgv in thisControl.Controls)
{
if (dgv.GetType() == typeof(DataGridView))
{
BuildWhiteboardDGV((DataGridView)dgv);
PopulateWhiteboardDGV((DataGridView)dgv);
wbDataGridView = (DataGridView)dgv;
wbDataGridView.CellMouseUp += new DataGridViewCellMouseEventHandler(wbDataGridView_CellMouseUp);
wbDataGridView.CellEndEdit += new DataGridViewCellEventHandler(wbDataGridView_CellEndEdit);
wbDataGridView.CurrentCellDirtyStateChanged += new EventHandler(wbDataGridView_CurrentCellDirtyStateChanged);
wbDataGridView.CellValueChanged += new DataGridViewCellEventHandler(wbDataGridView_CellValueChanged);
}
}
}
}
The events themselves are as follows:
void wbDataGridView_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (wbDataGridView.IsCurrentCellDirty)
{
wbDataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
void wbDataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
try
{
if (e.ColumnIndex >= 13 && e.ColumnIndex <= 15)
{
System.Drawing.Point cur = new System.Drawing.Point(e.ColumnIndex, e.RowIndex);
DataGridViewCheckBoxCell curCell = (DataGridViewCheckBoxCell)wbDataGridView[cur.X, cur.Y];
if (curCell.Value != null && (bool)(curCell.Value) == true)
{
MessageBox.Show("TRUE");
}
else if (curCell.Value != null && (bool)(curCell.Value) == false)
{
MessageBox.Show("FALSE");
}
else
{
MessageBox.Show("NULL");
}
}
return;
}
catch (Exception ex )
{
MessageBox.Show("wbDataGridView_CellValueChanged() ERROR - " + ex.Message + " --> " + ex.InnerException.ToString());
return;
}
}
Where am I going wrong?
OK.... I think I've sorted it.
In my CellMouseUp() event, I had not catered for the LEFT button.
Therefore, by now adding that, the CellValueChanged() event works correctly and captures the correct DataGridViewCheckCellColumn check state : TRUE when checked and FALSE when unchecked.
public void wbDataGridView_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left && e.RowIndex != -1) // added this and it now works
{
this.rowIndex = e.RowIndex;
this.colIndex = e.ColumnIndex;
this.wbDataGridView = (DataGridView)sender;
return;
}
if (e.Button == System.Windows.Forms.MouseButtons.Right && e.RowIndex != -1)
{
this.rowIndex = e.RowIndex;
this.colIndex = e.ColumnIndex;
this.wbDataGridView = (DataGridView)sender;
return;
}
}
Thanks for your comments though. Much appreciated.
Jobs a good un !!!!
I have WPF application where in the Ui I have a header check box and when it is checked all the body checkboxes are checked. When any checkbox is checked, Im doing some work that I need by calling the Background worker which works perfect. If I select any checkboxes individually without checking header then Background worker works fine.
Problem is when I check the header all the body checkboxes are checked and in this case the Background worker 'Run Worker completed' event is being executed even before 'do work' is executed which is breaking my code. Please help. Here is my code. RunJob is from command for button in front end.
public void RunJob(object obj)
{
obforSave = obj;
workerforRun = new BackgroundWorker();
workerforRun.WorkerReportsProgress = true;
workerforRun.DoWork += workerforRun_DoWork;
workerforRun.ProgressChanged += workerforRun_ProgressChanged;
workerforRun.RunWorkerCompleted += workerforRun_RunWorkerCompleted;
if (!workerforRun.IsBusy)
{
workerforRun.RunWorkerAsync();
}
}
//Special case header is checked Runwroker completed is executing before do work.
void workerforRun_DoWork(object sender, DoWorkEventArgs e)
{
IsValidationsComplete = false;
int count = 0;
//var obj = e.Argument;
if (IsRunJobAlreadyExecuted == false)
{
ResultExtract = JobEntities.Any(s => s.ExtractIsSelected != null && (bool)s.ExtractIsSelected);
var resultTransform = JobEntities.Any(x => x.TransformIsSelected != null && (bool)x.TransformIsSelected);
var resultLoad = JobEntities.Any(b => b.LoadIsSelected != null && (bool)b.LoadIsSelected);
//Check if any of the entities are either Extracted, Transformed or Loaded.
if (ResultExtract || resultTransform || resultLoad)
{
SaveJobConfigurationChanges(obforSave);
var jobEngine = new JobEngine();
var jobId = JobEntities[0].JobId;
jobEngine.ProcessJob(jobId);
MessageBox.Show("Job Execution Complete", "Run Job");
AllResults = GetJobConfigurationResults();
foreach (var item in AllResults)
{
if (item.ExtractIsSelected == true && item.ExtractStatus == "Completed Successfully")
{
count += Convert.ToInt32(item.ExtractRowsSelected);
}
if (item.TransformIsSelected == true && item.TransformStatus == "Completed Successfully")
{
count += Convert.ToInt32(item.TransformRowsSelected);
}
if (item.LoadIsSelected == true && item.LoadStatus == "Completed Successfully")
{
count += Convert.ToInt32(item.LoadRowsSelected);
}
}
workerforRun.ReportProgress(count);
//MessageBox.Show(count.ToString());
}
else
{
//When No Entity is Selected and the Run Button is pressed.
MessageBox.Show("Select an Entity First");
}
}
IsRunJobAlreadyExecuted = false;
}
void workerforRun_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progress = e.ProgressPercentage;
}
void workerforRun_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
{
/*When Header is checked and when the Run is clicked, you want to Uncheck the header back after completion.
This property is set in the CS file.*/
AllResults = GetJobConfigurationResults();
foreach (var item in AllResults)
{
item.ExtractIsSelected = false;
item.TransformIsSelected = false;
item.LoadIsSelected = false;
}
SaveTaskSelection();
JobEntitiesCollectionViewSource.Source = AllResults;
JobEntitiesCollectionViewSource.View.Refresh();
ExecuteFilteredEntitiesStoredProcedure();
IsValidateEnabled = AllResults.Any(p => p.ExtractStatus == "Completed Successfully");
}), DispatcherPriority.Background, null);
MessageBox.Show(progress.ToString());
IsValidationsComplete = true;
}
CS file:
public IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
var child = VisualTreeHelper.GetChild(depObj, i);
// If there is a child found and if the child is of the T type.
//Dont remove null check . If no check i
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
private IEnumerable<CheckBox> GetAllCheckBoxs()
{
var allCheckBoxes = FindVisualChildren<CheckBox>(UserControlJob);
return allCheckBoxes;
}
private void ChkHeaderExtract_OnChecked(object sender, RoutedEventArgs e)
{
var extractCheckBoxes = GetAllCheckBoxs();
var i = 0;
foreach (var chk in extractCheckBoxes)
{
if (i%3 == 0) // Since I have many sets of checkboxes and I want only the first set of checkboxes checked when header is clicked Im doing this.
{
chk.IsChecked = true;
}
i++;
}
}
I have a datatemplate in which i have a text block and speech synthesizer. Whwn i bind it with data the template spawns atleast 3 children. A speech synthesizer is activated on click of one checkbox. It works fine in normal conditions. But if i test it vigorously and try to play more than one synthesizer before initialization, it plays unexpected audio. And it continue even after exiting from that page.
I am sharing code for check box click event. Please suggest a solution.
private async void checkboxPlay_Click(object sender, RoutedEventArgs e)
{
// when _mediaCounter == 0, synthesizer is stopped or not played
// when _mediaCounter == 1, it is playing
// when _mediaVounter == 2, it is paused
Grid gd = (Grid)((sender as CheckBox).Parent as Grid).Parent;
var child = VisualTreeHelper.GetParent(gd);
try
{
if (sender is CheckBox)
{
if (_listElement.Count > 0)
{
if (sender != _listElement[_checkCounter].CheckBox && _listElement[_checkCounter].CheckBox != null)
{
_listElement[_checkCounter].MediaElement.Stop();
_mediaCounter = 0;
_timer.Stop();
_listElement[_checkCounter].Slider.Value = 0;
_description = string.Empty;
_listElement[_checkCounter].CheckBox.IsChecked = false;
}
}
CheckBox cb = sender as CheckBox;
Grid x = (Grid)VisualTreeHelper.GetParent(cb);
_mediaIndex = Convert.ToInt32(
x.DataContext.ToString().Substring(x.DataContext.ToString().Length - 1, 1)
) - 1;
_checkCounter = _mediaIndex;
if (_description != cb.DataContext.ToString())
{
cb.IsChecked = true;
_description = cb.DataContext.ToString();
_mediaCounter = 0;
_InitializeCheckbox(cb);
_InitializeMedia();
}
}
if (_mediaCounter == 0)
{
_mediaCounter = 1;
string desc = string.Empty;
SpeechSynthesizer synth = new SpeechSynthesizer();
SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync(_description.ToString());
_listElement[_checkCounter].MediaElement.SetSource(stream, stream.ContentType);
_listElement[_checkCounter].MediaElement.Play();
}
else if (_mediaCounter == 1)
{
_listElement[_checkCounter].MediaElement.Pause();
_timer.Stop();
_mediaCounter = 2;
}
else
{
_listElement[_checkCounter].MediaElement.Play();
_timer.Start();
_mediaCounter = 1;
}
}
catch
{
}
}
Have you tried using the MediaElement.CurrentState property?
MediaElement.CurrentState
here's a link
http://msdn.microsoft.com/En-US/Library/Windows/Apps/windows.ui.xaml.controls.mediaelement.currentstate
Is there a way to reference buttons using a numerical value in C#? I am trying to manipulate the text on buttons using one reusable method. Here is my current coding:
One button click method (there are a total of 16):
private void Card1_Click(object sender, EventArgs e)
{
buff = CardClick(1);
if (buff != null)
{
Card1.Text = buff;
}
}
And the reusable method (the code does have holes, it's in development):
private string CardClick(int card)
{
guesses[g++] = card; //alternate g
if ((guesses[0] != null) && (guesses[1] != null))
{
//Reset Card guesses[0]
//Reset Card guesses[1]
return null;
}
else
{
if (card > 8)
{
return map[2, card];
}
else
{
return map[1, card];
}
}
You can also use Controls.Find() to get a reference to your desired button based on its name:
int i = 1;
Control[] matches = this.Controls.Find("Card" + i.ToString(), true);
if (matches.Length > 0 && matches[0] is Button)
{
Button btn = (Button)matches[0];
// ... do something with "btn" ...
btn.PerformClick();
}
You can use an array of buttons
Button[] buttonArray = new Button[10];
You can get all the buttons from your form by Type and then extract an array:
public Button[] AllButtons()
{
var buttons = new List<Button>();
foreach (var control in this.Controls)
{
if (control.GetType() == typeof(Button))
buttons.Add((Button)control);
}
return buttons.ToArray();
}
In Silverlight, a little box is drawn around the currently HIGHLIGHTED (NOT Selected) item when you press up or down arrow or tab. I want to find out which item the little box is around so I can make it the selected item when the user presses tab. I spent three days on this, maybe someone else can use it.
void SelectorRapidAccessKeyBehavior_DropDownOpened(object sender, EventArgs e)
{
FindPopup();
}
private void FindPopup()
{
CleanUpPopupHandler();
pop = GetPopup(base.AssociatedObject);
if (pop != null && pop.Child != null)
{
pop.Child.KeyDown += AssociatedObject_KeyUp;
foreach (FrameworkElement c in Finder.FindVisualChildren<FrameworkElement>(pop.Child))
{
c.KeyDown += new KeyEventHandler(c_KeyDown);
}
}
}
void c_KeyDown(object sender, KeyEventArgs e)
{
int t = this.AssociatedObject.TabIndex;
Border ci = sender as Border;
if (e.Key == Key.Tab)
{
if (ci != null)
{
//this here is the magic line
var v = Finder.FindVisualChildren<FrameworkElement>((DependencyObject)pop.Child).Where(a => a.Opacity > 0 && a.Name == "FocusVisualElement" && a.Visibility == Visibility.Visible);//&& )
object o = v.First().DataContext;
int i = this.AssociatedObject.Items.IndexOf(o);
if (i > -1)
this.AssociatedObject.SelectedIndex = i;
pop.IsOpen = false;
DependencyObject d = Finder.FindParent<FloatableWindow>(this.AssociatedObject);
if (d == null)
d = Finder.FindParent<Window>(this.AssociatedObject);
Control c = Finder.FindVisualChildren<Control>(d).Where(a => a.TabIndex > t).OrderBy(a => a.TabIndex).FirstOrDefault();
if (c == null)
c = Finder.FindVisualChildren<Control>(d).OrderBy(a => a.TabIndex).FirstOrDefault();
if (c != null)
c.Focus();
}
}
}
Just add a KeyDown event to the items (possibly easier said than done) and select the item if the Key is Tab, the event will be fired on the one that is focused (has the box around it), e.g.
<ComboBox Loaded="ComboBox_Loaded">
<ComboBoxItem>1</ComboBoxItem>
<ComboBoxItem>2</ComboBoxItem>
<ComboBoxItem>3</ComboBoxItem>
<ComboBoxItem>4</ComboBoxItem>
<ComboBoxItem>5</ComboBoxItem>
</ComboBox>
private void ComboBoxItem_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Tab)
{
var cbi = sender as ComboBoxItem;
var cb = cbi.Parent as ComboBox;
cb.SelectedItem = cbi;
e.Handled = true;
cb.IsDropDownOpen = false;
}
}
private void ComboBox_Loaded(object sender, RoutedEventArgs e)
{
var cb = sender as ComboBox;
foreach (var item in cb.Items)
{
(item as ComboBoxItem).KeyDown += ComboBoxItem_KeyDown;
}
}
In WPF i would know of some cleaner ways to attach the events, maybe you can think of something.
void SelectorRapidAccessKeyBehavior_DropDownOpened(object sender, EventArgs e)
{
FindPopup();
}
private void FindPopup()
{
CleanUpPopupHandler();
pop = GetPopup(base.AssociatedObject);
if (pop != null && pop.Child != null)
{
pop.Child.KeyDown += AssociatedObject_KeyUp;
foreach (FrameworkElement c in Finder.FindVisualChildren<FrameworkElement>(pop.Child))
{
c.KeyDown += new KeyEventHandler(c_KeyDown);
}
}
}
void c_KeyDown(object sender, KeyEventArgs e)
{
int t = this.AssociatedObject.TabIndex;
Border ci = sender as Border;
if (e.Key == Key.Tab)
{
if (ci != null)
{
//this here is the magic line
var v = Finder.FindVisualChildren<FrameworkElement>((DependencyObject)pop.Child).Where(a => a.Opacity > 0 && a.Name == "FocusVisualElement" && a.Visibility == Visibility.Visible);//&& )
object o = v.First().DataContext;
int i = this.AssociatedObject.Items.IndexOf(o);
if (i > -1)
this.AssociatedObject.SelectedIndex = i;
pop.IsOpen = false;
DependencyObject d = Finder.FindParent<FloatableWindow>(this.AssociatedObject);
if (d == null)
d = Finder.FindParent<Window>(this.AssociatedObject);
Control c = Finder.FindVisualChildren<Control>(d).Where(a => a.TabIndex > t).OrderBy(a => a.TabIndex).FirstOrDefault();
if (c == null)
c = Finder.FindVisualChildren<Control>(d).OrderBy(a => a.TabIndex).FirstOrDefault();
if (c != null)
c.Focus();
}
}
}