I've made a TextBox that retains what you type, and when you click the button associated it gives you a messagebox. When people want to click no, I want the button to change location so people cannot click it so they are forced to click yes,Well the problem is mousehover works just 1 time and does not go back to initial position after i leave my pointer out. Can you help me? Here is the code:
{
MsgBox = new CustomMsgBox();
MsgBox.label1.Text = Text;
MsgBox.button1.Text = btnOK;
MsgBox.button2.Text = btnCancel;
MsgBox.Text = Caption;
result = DialogResult.No;
MsgBox.ShowDialog();
return result;
}
private void button2_Click(object sender, EventArgs e)
{
button2.Location = new Point(25, 25);
}
private void button2_MouseHover(object sender, EventArgs e)
{
button2.Location = new Point(+50, +50);
}
private void button2_MouseLeave(object sender, EventArgs e)
{
button2.Location = new Point(+100, +100);
}
You should not use MouseLeave because when you move the button in the MouseHover, the button will move so the mouse will leave the button area. Meaning the No button will flip from the original position to the new position and back again all the time. What you could do is use the MouseMove to see if the user moved away from the area where the Button2 was originally and then move it back. Or include a non-visible control, like an empty label behind the button2. And set the MouseLeave on the label instead.
Oh and don't forget to set button2.TabStop = false, otherwise the user can use tab to get to the button.
Made a quick and dirty proof of concept for this, hope that helps ;)
public partial class Form1 : Form
{
private Rectangle buttonRectangle;
private bool checkRectangle = false;
public Form1()
{
InitializeComponent();
button2.TabStop = false;
buttonRectangle = button2.ClientRectangle;
buttonRectangle.Location = button2.Location;
}
private void button2_Click(object sender, EventArgs e)
{
button2.Location = new Point(25, 25);
}
private void button2_MouseHover(object sender, EventArgs e)
{
button2.Location = new Point(50, 50);
checkRectangle = true;
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (!checkRectangle)
{
return;
}
if (!buttonRectangle.Contains(e.X, e.Y))
{
checkRectangle = false;
button2.Location = buttonRectangle.Location;
}
}
}
The buttonRectangle is set based on where the button is found during construction of the form. It has a contains method that can be used to check if a certain point (mouse move) is contained in it.
I also set the button2.TabStop to false so it will no longer be active during tab cycles.
When your hover (can change this to mouse enter, but just used your code) event fires, I set checkRectangle to true. I use this in the mouse move event handler to see if anything should be checked (prevents from doing anything when the mouse is not "over" the button).
If the buttonRectangle and the mouse location are not intersected this means we left the area where the button was, so we can move the button back.
Related
I am using a textbox for a login window. I want the textbox to display "Username" in light grey so the user knows to use that box to type in the username. Whenever the user clicks on the textbox even if it's in the middle of the word username I want the cursor to go to the first position and username will disappear when they start typing. I tried using the PreviewMouseDown event but it only works inside breakpoints but doesn't trigger at all outside it. Using the PreviewMouseUp event it works, but other caret positions can be selected before the cursor jumps to the beginning. I want it to appear like the user is unable to select any cursor position besides the first. This is the code I've tried.
private bool textboxuserfirstchange = true;
private void eventTextChanged(object sender, TextChangedEventArgs e)
{
if (textBoxUser.Text != "Username")
{
if (textboxuserfirstchange)
{
textBoxUser.Text = textBoxUser.Text[0].ToString();
textBoxUser.SelectionStart = 1;
textBoxUser.Opacity = 100;
}
textboxuserfirstchange = false;
}
}
private void eventPreviewMouseDown(object sender, MouseButtonEventArgs e)
{
if (textboxuserfirstchange)
{
textBoxUser.Focus();
textBoxUser.Select(0, 0); //None of these working
textBoxUser.SelectionStart = 0;
textBoxUser.CaretIndex = 0;
}
}
You could for example handle the GotKeyboardFocus and PreviewTextInput event. Something like this:
private const string Watermark = "Username";
private void TextBox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
if (textBoxUser.Text == Watermark)
textBoxUser.Dispatcher.BeginInvoke(new Action(() => textBoxUser.CaretIndex = 0), DispatcherPriority.Background);
}
private void textBoxUser_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (textBoxUser.Text == Watermark)
textBoxUser.Text = string.Empty;
}
The button click method mentioned below, can be used to start playing an audio file. However, once it starts it cannot be paused, if I click the button again the song will start to play again, from the beginning. Please let me know the way to stop it using Enter Key.
private void btn_reproducir_Click(object sender, EventArgs e)
{
WindowsMediaPlayer myplayer = new WindowsMediaPlayer();
myplayer.URL = #"C:\song.mp3";
myplayer.controls.play();
}
Please try this code.
public partial class Form1 : Form
{
// Media player object
WindowsMediaPlayer myplayer = new WindowsMediaPlayer();
public Form1()
{
InitializeComponent();
myplayer.URL = #"C:\song.mp3";
}
private void reproducir_Click(object sender, EventArgs e)
{
myplayer.controls.play();
}
private void btnStop_Click(object sender, EventArgs e)
{
myplayer.controls.stop();
}
private void btnPause_Click(object sender, EventArgs e)
{
myplayer.controls.pause();
}
}
If you want to use the same button to play and pause the music, you can use a flag to determine its behavior:
bool isPlaying = false;
private void btn_reproducir_Click(object sender, EventArgs e)
{
WindowsMediaPlayer myplayer = new WindowsMediaPlayer();
myplayer.URL = #"C:\song.mp3";
if(isPlaying)
{
myplayer.controls.pause();
isPlaying = false;
}
else
{
myplayer.controls.play();
isPlaying = true;
}
}
If you want to use the enter key to click the button from anywhere in the form, simply set the form's "AcceptButton" to the button you want clicked. As long as the control that currently has focus does not use the enter key, then pressing the enter key will automatically click the AcceptButton. A scenario where this would not work would be if a multi-line text box has focus. A multi-line text box allows you to press enter to start a new line, so the AcceptButton would not be clicked in this case.
Additionally, you can always use the tab key to tab to the button and then press enter once the button is highlighted.
My goal is to have multiple buttons whose text can be switched on the screen through dragging the text from one button to another (it's not necessary that the buttons themselves be switched, only the text on them, although if it's easier to switch the buttons themselves, that's fine). I have tried to follow this MSDN article but as soon as I actually begin to drag, I get a "no" symbol (an O with a / through it). Am I missing something? (Code below)
Thanks in advance!
public partial class Form1 : Form
{
Button button1 = new Button();
Button button2 = new Button();
public Form1()
{
InitializeComponent();
button1.Text = "Button 1";
button2.Text = "Button 2";
button2.Location = new Point(100, 0);
this.Controls.Add(button1);
this.Controls.Add(button2);
button1.MouseDown += new MouseEventHandler(button_MouseDown);
button2.MouseDown += new MouseEventHandler(button_MouseDown);
button1.DragEnter += new DragEventHandler(button_DragEnter);
button2.DragEnter += new DragEventHandler(button_DragEnter);
button1.DragDrop += new DragEventHandler(button_DragDrop);
}
private void button_MouseDown(object sender, MouseEventArgs e)
{
((Button)sender).DoDragDrop(((Button)sender).Text, DragDropEffects.Move);
}
private void button_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Move;
}
private void button_DragDrop(object sender, DragEventArgs e)
{
//I'm not sure what goes here, but I can figure that out through experimentation
}
}
So it turns out I just had to do some more research. Adding button.AllowDrop = true for both buttons solved the issue
I have a problem with my winforms C# project.
I want to move a new (custom) button around the form (at run time).
How can I do that?
Button[] buttons = new Button[1000];
int counter = 0;
Button myText = new Button();
private void button2_Click(object sender, EventArgs e)
{
Button myText = new Button();
myText.Tag = counter;
myText.Location = new Point(x2,y2);
myText.Text = Convert.ToString(textBox3.Text);
this.Controls.Add(myText);
myText.MouseMove += new MouseEventHandler(myText_MouseMove);
myText.MouseDown += new MouseEventHandler(myText_MouseDown);
buttons[counter] = myText;
counter++;
}
public void myText_MouseMove(object sender, MouseEventArgs e)
{
int s = e.GetHashCode();
int check = 0;
for (int i = 0; i < counter; i++)
{
if (buttons[i].GetHashCode() == s)
check = i;
}
if (e.Button == MouseButtons.Left)
{
buttons[check].Left += e.X - move.X;
buttons[check].Top += e.Y - move.Y;
}
}
void myText_MouseDown(object sender, MouseEventArgs e)
{
move = e.Location;
}
I use the code above to create the new button and I am trying to move it around the form.
If I code for just 1 button I am able to move it but, I want to be able to do this for more buttons as well.
Try this
public void myText_MouseMove(object sender, MouseEventArgs e)
{
Button button = (Button)sender;
if (e.Button == MouseButtons.Left)
{
button .Left += e.X - move.X;
button .Top += e.Y - move.Y;
}
}
I've come across this thread while doing something similar.
Even though the thread is quite old; I'm sharing the way I've achieved this.
Notes:
Unlike the operator question above; in the example bellow; I'm not using a Button[] (array) with 1000 buttons; (but this can be easily changed).
In the example bellow I have:
A Form with 1 Button on it.
When this button is clicked; it will create a new (Custom) Button
(hence; having two button click events in the code simply for the test purpose).
Bellow you can find: A way to generate the button; and so how to drag it around the form.
/* Variables */
// Used to Store the Mouse Location on the Screen when Button is Clicked
private Point mouseDownLocation;
// Used to know if the Button can be Moved.
private bool isMoveable = false;
// Used to prevent clicking the button when being dragged
private bool clickEnabled = true;
/// <summary> Occurrs when the visible button on the Form is clicked. </summary>
private void Button_Click(object sender, EventArgs e)
{
// Create a variable to set the Size of the new Button.
Size size = new Size(100, 100);
// Create the Button. Specifying the Button Text and its Size.
CreateButton("Button Text", size);
}
/* Custom Button : Create & Configure the Button */
private void CreateButton(string btnText, Size btnSize)
{
// Create the Button instance:
Button btn = new Button();
// Custom Button Style Configuration Code.
// i.e: FlatStyle; FlatAppearance; BackColor; ForeColor; Text; Size; Location; etc...
btn.FlatStyle = FlatStyle.Standard;
btn.FlatAppearance.BorderColor = Color.White;
btn.BackColor = Color.Purple;
btn.ForeColor = Color.White;
btn.Text = btnText;
btn.Size = btnSize;
btn.Location = new Point(100, 100);
// Custom Button Event.
btn.Click += new EventHandler(CustomButton_Click);
btn.MouseDown += new MouseEventHandler(CustomButton_MouseDown);
btn.MouseMove += new MouseEventHandler(CustomButton_MouseMove);
btn.MouseUp += new MouseEventHandler(CustomButton_MouseUp);
// Add Button to Control Collection.
Controls.Add(btn);
// Show Button.
btn.Show();
}
/* Custom Button Events */
/// <summary> Occurrs whenever the Custom Button is Clicked </summary>
private void CustomButton_Click(object sender, EventArgs e)
{
if (clickEnabled)
{
// Note: The "for" loop bellow lets you get the current button; so you can drag it.
Button btn = (Button)sender;
// Iterate over the Form Controls
for (int i = 0; i < Controls.Count; i++)
{
// If the Button Clicked Corresponds to a Found Index in Control Collection...
if (i == Controls.IndexOf(btn))
{
// Perform Corresponding Button Action.
MessageBox.Show(btn.Name + " Clicked!");
}
}
}
}
/// <summary> Occurrs whenever Left Mouse Button Clicks the Button and is Kept Down. </summary>
private void CustomButton_MouseDown(object sender, MouseEventArgs e)
{
// Check if Left Mouse Button is Clicked.
if (e.Button == MouseButtons.Left)
{
// Set mouseDownLocation (Point) variable, according to the current mouse location (X and Y).
mouseDownLocation = e.Location;
// Enable the hability to move the Button.
isMoveable = true;
}
}
/// <summary> Occurrs whenever Left Mouse Button is Down and Mouse is Moving the Button. </summary>
private void CustomButton_MouseMove(object sender, MouseEventArgs e)
{
Button btn = (Button)sender;
// If the hability to move the button is "true" and the mouse button used to drag the button is the left mouse button:
if (isMoveable)
{
if (e.Button == MouseButtons.Left)
{
// Set the Button location X and Y...
btn.Left = e.X + btn.Left - mouseDownLocation.X;
btn.Top = e.Y + btn.Top - mouseDownLocation.Y;
}
}
// Disable Click hability (See: Note at the end of this post).
clickEnabled = false;
}
/// <summary> Occurrs whenever Left Mouse Button is not longer being hold down (Left Mouse Button is Up). </summary>
private void CustomButton_MouseUp(object sender, MouseEventArgs e)
{
// Disables the hability to move the button
isMoveable = false;
clickEnabled = true;
}
Note: The Custom Button Click interferes with the MouseDown Event. In a "simple" manner:
I updated the code by including a boolean value to prevent clicking the button when actually it is being dragged.
Hope this helps you out understanding how to accomplish this feature.
Hope this helps people out achieving this goal.
I have a fom which has one user control docked to fill.
this user control displays different images.each image has Id and I have a list of imageId vs imageDetail object dictionary.
Mouse Move event of this user control is captured and i am displaying current X and Y position of mouse in tool tip.
I also want to display image detail in tool tip when user keeps the mouse over image for some time.
I tried to do this with Mouse Hover event but it only raised when mouse enters in user control bound. after this if i move mouse within user control mouse hover event does not fire...
How can i display current X, Y position along image detail in tool tip.
is there any way to simulate Mouse Hover event within Mouse Move using some timer.
Is there any sample code..
I solved this problem by
public partial class Form1 : Form
{
Timer timer;
bool moveStart;
int count = 0;
Point prev;
public Form1()
{
InitializeComponent();
timer = new Timer();
timer.Interval = 1000;
timer.Tick += new EventHandler(timer_Tick);
}
void timer_Tick(object sender, EventArgs e)
{
this.timer.Stop();
this.moveStart = false;
this.toolTip1.SetToolTip(this, string.Format("Mouse Hover"));
this.textBox1.Text = (++count).ToString();
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (this.prev.X == e.X && this.prev.Y == e.Y)
return;
if (moveStart)
{
this.prev = new Point(e.X, e.Y);
this.timer.Stop();
this.toolTip1.SetToolTip(this, string.Format("Mouse Move\nX : {0}\nY : {1}", e.X, e.Y));
this.timer.Start();
}
else
{
moveStart = true;
}
}
}
The simplest way would be to call the MouseOver subroutine from the MouseMove subroutine as such:
void MouseMove(object sender, MouseEventArgs e)
{
//Call the MouseHover event
MouseHover(sender, e);
}
void MouseHover(object sender, EventArgs e)
{
//MouseHover event code
}
If you want more control over when and how to display your tooltip, however, you'll need to do something similar to the following:
Declare a listening variable at class level.
Hook to the MouseHover event so the listening variable is turned on when the mouse enters.
Hook to the MouseLeave event so the listening variable is turned off when the mouse leaves.
Put your tooltip code in the MouseMove handler so it displays your tooltip if the listening variable is on.
Here's some code to demonstrate what's I outlined above.
class Form1
{
bool showPopup = false;
void MouseHover(object sender, EventArgs e)
{
showPopup = true;
}
void MouseLeave(object sender, EventArgs e)
{
showPopup = false;
toolTip.Hide(this);
}
void MouseMove(object sender, MouseEventArgs e)
{
if (showPopup)
{
toolTip.Show("X: " + e.Location.X + "\r\nY: " + e.Location.Y,
this, e.Location)
}
}
}
Of course, you'll have to add a ToolTip with the name toolTip and associate the various methods (subroutines) with the appropriate events of your control (Form, PictureBox, etc).