custom tooltip in c# .net win forms - c#

I am looking to simulate a custom tooltip the like of you see in websites using c# .NET 4.5 windows forms.This tooltip will basically show status of some Tasks like how many tasks are pending,tasks in process, completed etc.To do this i am using a borderless win form.This winform will have some texts, images etc.I want it to reveal itself on button's mouseHover event and disappear on MouseLeave event.My problem is that on Mousehover event numerous instances of that tooltip form is getting generated and on MouseLeave they are not getting closed.My code is
private void B_MouseHover(object sender, EventArgs e)
{
frmSecQStatToolTipDlg tooltip = new frmSecQStatToolTipDlg();
tooltip.Location = this.PointToScreen(new Point(this.Left, this.Bottom));
tooltip.Show();
}
private void B_MouseLeave(object sender, EventArgs e)
{
frmSecQStatToolTipDlg tooltip = new frmSecQStatToolTipDlg();
tooltip.Close();
}
My code is not working, hence please tell me how to do this the correct way.Thanks

You're generating a new instance of the form class every time you get a hover event, and every time you get a leave event. If you want to continue to use this approach I would recommend you use a variable on your main form object to store the reference to your tooltip form. Secondly, you need to not generate a new instance whenever the event handler is called, but only when necessary. I would create your instance the first time your Hover event is called for a particular control, and then dispose of it when your Leave handler is called -- this is under the assumption that the tooltip dialog's constructor loads up different information for each control being hovered over. Like so:
frmSecQStatToolTipDlg f_tooltip;
private void B_MouseHover(object sender, EventArgs e)
{
if(frmSecQStatToolTipDlg == null)
{
f_tooltip = new frmSecQStatToolTipDlg();
}
tooltip.Location = this.PointToScreen(new Point(this.Left, this.Bottom));
tooltip.Show();
}
private void B_MouseLeave(object sender, EventArgs e)
{
if(f_tooltip != null)
{
f_tooltip.Close();
f_tooltip = null;
}
}

You should keep a global field for this form, and should not dispose or close it. Just hide it on some events and show again.
Sample Code:
frmSecQStatToolTipDlg tooltip;
private void B_MouseHover(object sender, EventArgs e)
{
if(frmSecQStatToolTipDlg == null)
{
tooltip = new frmSecQStatToolTipDlg();
}
tooltip.Location = this.PointToScreen(new Point(this.Left, this.Bottom));
tooltip.Show();
}
private void B_MouseLeave(object sender, EventArgs e)
{
if(frmSecQStatToolTipDlg != null)
{
tooltip.Hide();
}
}
With this logic you'll not have to create tooltip instance again and again and it will not take time to popup if you frequently do this activity.

Declare your tooltip once as readonly and use it without asking anytime if it is null or not.
If you need to Dispose it, implement the IDisposable pattern:
https://msdn.microsoft.com/en-us/library/b1yfkh5e(v=vs.110).aspx
private readonly frmSecQStatToolTipDlg _tooltip = new frmSecQStatToolTipDlg() ;
private void B_MouseHover(object sender, EventArgs e)
{
_tooltip.Location = this.PointToScreen(new Point(this.Left, this.Bottom));
_tooltip.Show();
}
private void B_MouseLeave(object sender, EventArgs e)
{
_tooltip.Hide();
}

Related

c# referencing a label from another method

I want if mouse leave the visible status change to false,but I get this error message:
Error CS7036 There is no argument given that corresponds to the required formal parameter 'e' of 'Form1.Repair_MouseLeave(object, EventArgs, Label)'
How shoudl I fix it?
private void Repair_MouseHover(object sender, EventArgs e)
{
Label RepairText = new Label();
RepairText = new Label();
RepairText.Location = new Point(161, 12);
RepairText.Text = "This what the program will do";
this.Controls.Add(RepairText);
RepairText.AutoSize = true;
Repair_MouseLeave(RepairText);
}
private void Repair_MouseLeave(object sender, EventArgs e,Label repairtext)
{
repairtext.Visible = false;
}
First of all, we need to set our event handlers for the MouseHover and MouseLeave methods for the Repair control. I am assuming you know how to do this. Still,
binding to the events of Repair control can be achieved using the Properties window of your Form in design mode. Set event handlers to both MouseHover and MouseLeave.
As far as I can see, you are trying to display a label with some text when the mouse is hovering over this Repair control and want to hide it when the mouse leaves it. But you are handling it incorrectly. First of all, calling MouseLeave from inside MouseHover would immediately hide your new label and it would not be displayed at all.
And your method signature for Repair_MouseLeave is also incorrect. A standard event handler takes two parameters: (object sender, EventArgs e)
Implement your event handlers like the following, having the new label repairText as an instance member of your class:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private Label repairText;
private void Repair_MouseHover(object sender, EventArgs e)
{
if(repairText == null)
{
repairText = new Label();
repairText.Location = new Point(161, 12);
repairText.Text = "This what the program will do";
repairText.AutoSize = true;
this.Controls.Add(repairText);
}
repairText.Visible = true;
}
private void Repair_MouseLeave(object sender, EventArgs e)
{
if(repairText != null)
{
repairText.Visible = false;
}
}
}

c# Detect mouse clicks anywhere (Inside and Outside the Form)

Is this possible to detect a mouse click (Left/Right) anywhere (Inside and Outside the Form) in an if statement? And if it's possible, how?
if(MouseButtons.LeftButton == MouseButtonState.Pressed){
...
}
Here is a starter, if I understood your needs of "clicking from outside the window" and Hans Passant's suggestion doesn't fit your needs. You might need to add an event handler for Form1_Click.
CAUTION: This code is provided to illustrate the concept. The threading synchronization in this sample is not 100% correct. Check the history of this answer for an attempt at a more "threading correct" one that sometimes throws exceptions. As an alternative, to get rid of all threading issues, you could have the task in StartWaitingForClickFromOutside be instead always running (aka be always in "listen" mode) as opposed to trying to detect the "within the form" or "outside the form" states and starting/stopping the loop accordingly.
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.MouseLeave += Form1_MouseLeave;
this.Leave += Form1_Leave;
this.Deactivate += Form1_Deactivate;
this.MouseEnter += Form1_MouseEnter;
this.Activated += Form1_Activated;
this.Enter += Form1_Enter;
this.VisibleChanged += Form1_VisibleChanged;
}
private AutoResetEvent are = new AutoResetEvent(false);
// You could create just one handler, but this is to show what you need to link to
private void Form1_MouseLeave(object sender, EventArgs e) => StartWaitingForClickFromOutside();
private void Form1_Leave(object sender, EventArgs e) => StartWaitingForClickFromOutside();
private void Form1_Deactivate(object sender, EventArgs e) => StartWaitingForClickFromOutside();
private void StartWaitingForClickFromOutside()
{
are.Reset();
var ctx = new SynchronizationContext();
var task = Task.Run(() =>
{
while (true)
{
if (are.WaitOne(1)) break;
if (MouseButtons == MouseButtons.Left)
{
ctx.Send(CLickFromOutside, null);
// You might need to put in a delay here and not break depending on what you want to accomplish
break;
}
}
});
}
private void CLickFromOutside(object state) => MessageBox.Show("Clicked from outside of the window");
private void Form1_MouseEnter(object sender, EventArgs e) => are.Set();
private void Form1_Activated(object sender, EventArgs e) => are.Set();
private void Form1_Enter(object sender, EventArgs e) => are.Set();
private void Form1_VisibleChanged(object sender, EventArgs e)
{
if (Visible) are.Set();
else StartWaitingForClickFromOutside();
}
}
}
If I understood you incorrectly, you might find this useful: Pass click event of child control to the parent control
When user clicks outside the form control, it losses the focus and you can make use of that.which means you have to use the _Deactivate(object sender, EventArgs e) event of the form control to make this work. Since which will trigger when the form loses focus and is no longer the active form. Let Form1 be the form, then the event will be like the following:
private void Form1_Deactivate(object sender, EventArgs e)
{
// Your code here to handle this event
}
One method is to cover the entire screen with a borderless form with the properties set to transparent (a few percent above completely transparent, not sure if total transparency works but you won't notice the difference) and also set to topmost. Then use the events from the form. As soon as a click is detected this will not affect anything underneath the form (which in my application is something I want to happen) but the form could be closed and another mouse click simulated a fraction of a second later to activate the controls that are underneath. I had no problem using the windows API to use mouse hooks in VB6 but cannot seem to find something that works in c# with the 2019 version of .NET so this is a good workaround. Of course to be really clever you could use an irregular forms method to make the transparent form the same shape as the mouse and follow it.
Note: I have just found the complete code to do it using hooks that mere mortals can get up and running at once! KeyboardMouseHooks C# Library - CodePlex Archive
PS if you use my (dumb) method remember to create an escape key or button or you will have to restart your computer unless the form is programmed to disappear for real clicks as suggested!
I know this is late but maybe it helps someone. Using the MouseEventArgs of the MouseUp event of any control you can check for mouse button and wheel among other things. Here is an example.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.MouseUp += Form1_MouseUp;
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Left)
{
DoSomething_LeftClick();
}
else if(e.Button == MouseButtons.Right)
{
DoSomething_RightClick();
}
}
private void DoSomething_LeftClick()
{
//Here some code
}
private void DoSomething_RightClick()
{
//Here some code
}
}

adding an action for click event on picturebox in c#

I get a pictureboxe and try to add it an action to change background Image upon click event happen, but there is no action. So, this is the code:
pieces bishopBB = new pieces();
public Form1()
{
// object of picturebox
bishopBB.Location = new Point(300, 455);
bishopBB.Parent = this;
bishopBB.Click += new System.EventHandler(pictureboxes_Click)
InitializeComponent();
}
private void pictureboxes_Click(object sender, EventArges e)
{
backgroundImage = Properties.Resources.black;
}
Looking at the name and other indicators I would assume (and hope) that pictureboxes_Click is a common click handler for many PictureBoxes.
So to access the one that has been clicked you need to cast sender to PictureBox and then set the BackgroundImage:
private void pictureboxes_Click(object sender, EventArges e)
{
((PictureBox)sender).BackgroundImage = Properties.Resources.black;
}
I'm a little amazed though that your spelling of backgroundImage compiles. The correct spelling BackgroundImage refers to the current class, usually the Form and it should also show, unless your Form has a black background already..
To change the current image of the PictureBox control, you need to refer to the control and reference the BackgroundImage property (not 'backgroundImage'):
private void pictureboxes_Click(object sender, EventArges e)
{
this.pictureboxes.BackgroundImage = Properties.Resources.black;
}
To change the background image of the form:
private void pictureboxes_Click(object sender, EventArgs e)
{
this.BackgroundImage = Properties.Resources.black;
}
To do this you can use the on_click property of the picturebox. You can then use the like picbox.image = whatever the image location is

Is there a better way to close buttons on click?

I'm a beginner and have an assignment in which I must program the game of NIM. I begin with 15 "tokens" and at each turn a maximum of three can be removed, or "hidden". So far I am hiding these tokens on click by doing the following.
private void button1_Click(object sender, EventArgs e)
{
button1.Visible = false;
}
private void button2_Click(object sender, EventArgs e)
{
button2.Visible = false;
}
I simply copied and pasted that multiple times and changed the button numbers so that my buttons will close on click. This might be obvious, but is there a more efficient way to do this, instead of having 15 button close methods?
You can use the same click event for every single button, and make use of the sender object, casting it to Button:
private void buttonsToClose_Click(object sender, EventArgs e)
{
((Button)sender).Visible = false;
}
Then just add that handler to every single button you want to close itself on click.
Note, though, that this will throw an InvalidCastException if you or anyone else uses this handler on an object that is not a Button, so if you're actually going to use this code I would add some sort of conditional to check the real type of the sender.
Additionally, you could reuse this for any Control object by casting sender to Control instead, given that Button inherits from Control, and all Control objects have the Visible property. Here's an example, with a conditional to guard against an invalid cast:
private void controlToMakeInvisible_Click(object sender, EventArgs e)
{
if (sender.GetType() == typeof(Control))
{
((Control)sender).Visible = false;
}
}
A final note - it seems from your post like you may have a slight misunderstanding about the way events are created and wired in with objects in Windows Forms. If you go into the Designer, add a click event, and see it pop into your Form code as follows:
private void button1_Click(object sender, EventArgs e)
the name of this method has no bearing on its function. The button1 part of button1_Click doesn't actually have any logical linkage with the Button button1 - it's just the default name assigned by the Designer. The actual assignment of the method button1_Click to the Button.Click event is auto-generated into your Form's Designer.cs method.
The point of this is that if you copy and paste button1_Click and change every incidence of button1 with button2, like so:
private void button2_Click(object sender, EventArgs e)
{
button2.Visible = false;
}
it's not going to fire when button2 gets clicked. In actual fact, it's never going to fire at all, because the method hasn't actually been connected to any controls/events.
just call your event in a foreach loop.
private void Form1_Load(object sender, EventArgs e)
{
foreach (var button in Controls.OfType<Button>())
{
button.Click += button_Click;
}
}
void button_Click(object sender, EventArgs e)
{
((Control) sender).Visible = false;
}
if you change:
Controls.OfType<Button>()
to
Controls.OfType<Control>()
it will set visible to false for any Control. so you can control what item you want the event to be raised for easily.
OfType summary: Filters the elements of an IEnumerable based on a specified type.

how to generate a SelectionRangeChanged Event Programatically ChartControl WinForms

want to create a selectionRangeChanged event programatically not really getting how to do it
private void btn_10D_Click(object sender, EventArgs e)
{
double varRange = 10;
double var_Sel1 = DatesX[0].ToOADate();
Chart1.ChartAreas["ChartArea1"].CursorX.IsUserEnabled = true;
Chart1.ChartAreas["ChartArea1"].CursorX.IsUserSelectionEnabled = true;
Chart1.ChartAreas["ChartArea1"].CursorX.SelectionColor = Color.LightGray;
Chart1.ChartAreas["ChartArea1"].CursorX.SelectionStart = var_Sel1;
Chart1.ChartAreas["ChartArea1"].CursorX.SelectionEnd = varRange + var_Sel1;
Chart1.ChartAreas["ChartArea1"].CursorX.Position = varRange + var_Sel1;
Chart1.SelectionRangeChanged += new EventHandler<CursorEventArgs>(Chart1_SelectionRangeChanged);
}
void Chart1_SelectionRangeChanged(object sender, CursorEventArgs e)
{
throw new NotImplementedException();
}
thank you
For all events in C# is true that if class creator did not make extra effort to allow event firing form outside of class it is impossible to fire them.
According to MSDN
Chart.SelectionRangeChanged event Occurs when the selection start position or end position is changed.
But from my tests I can see that it is fired only if it is changed by user not program.
If I understand your intention correctly you want to handle those small buttons under your chart and btn_10D_Click method is a click handler for one of them. Try to move this line
Chart1.SelectionRangeChanged += new EventHandler<CursorEventArgs>(Chart1_SelectionRangeChanged);
to your constructor and ensure it is called once (remove it form other handlers). This will ensure your code is executed when user changes selection. If you want to execute same code for your button you should simply extract handler contents to method and call it form button click handler.
void Chart1_SelectionRangeChanged(object sender, CursorEventArgs e)
{
DoSomething(/*some arguments if you need them*/);
}
private void btn_10D_Click(object sender, EventArgs e)
{
\\your code
DoSomething();
}

Categories

Resources