MouseLeave detection not working with ImageForm - c#

I've got a smaller image in my form. When the user hovers over the image it brings up a larger view of the image (that follows the mouse, but stays a certain distance from the mouse). In order to do this I am generating a Form with no FormBorderStyles when the cursor hovers the image.
The problem I'm running into is that the first form doesn't seem to detect any longer that the mouse is hovering or leaving the PictureBox once the form activates. The Form also doesn't follow the cursor.
Here is the slimmed down version of what I've got:
C#
bool formOpen = false;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
pictureBox1.MouseHover += pictureBox1_MouseHover;
pictureBox1.MouseLeave +=pictureBox1_MouseLeave;
}
void pictureBox1_MouseHover(object sender, EventArgs e)
{
if (formOpen == false)
{
Form form = new Form();
form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
form.BackColor = Color.Orchid;
//Show the form
form.Show();
form.Name = "imageForm";
this.AddOwnedForm(form);
//Set event handler for when the mouse leaves the image area.
//form.MouseLeave += form_MouseLeave;
//Set the location of the form and size
form.BackColor = Color.Black;
form.Dock = DockStyle.Fill;
form.Size = new Size(30, 30);
form.BackgroundImageLayout = ImageLayout.Center;
this.TopMost = true;
formOpen = true;
form.Location = new Point(Cursor.Position.X, Cursor.Position.Y);
}
}
private void pictureBox1_MouseLeave(object sender, EventArgs e)
{
//MessageBox.Show("Worked");
}
}

The MouseLeave (and other events) was not recognized because the opening of the popup window and especially making it topmost=true took away the focus from the original form and its PictureBox.
It also didn't move because not code for moving was provided..
Here are a few changes that will make the form move:
You need a reference to it at the form1 level
you need to move it in the MouseMove event
Note that Hover is a once-only type of event. It fires only once until you leave the control.. (Note: Setsu has switched from Hover to Enter. This works fine, but lacks the short delay before showing the 2nd Form. If you want that back you can either switch back to Hover or you can fake the hover delay by a Timer, which is what I often do.)
// class level variable
Form form;
private void Form1_Load(object sender, EventArgs e)
{
pictureBox1.MouseEnter += pictureBox1_MouseEnter;
pictureBox1.MouseLeave +=pictureBox1_MouseLeave;
pictureBox1.MouseMove += pictureBox1_MouseMove; // here we move the form..
}
// .. with a little offset. The exact numbers depend on the cursor shape
void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if ((form != null) && form.Visible)
{
form.Location = new Point(Cursor.Position.X + 5, Cursor.Position.Y + 5);
}
}
void pictureBox1_MouseEnter(object sender, EventArgs e)
{
// we create it only once. Could also be done at startup!
if (form == null)
{
form = new Form();
form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
//form.BackColor = Color.Orchid;
form.Name = "imageForm";
this.AddOwnedForm(form);
form.BackColor = Color.Black;
form.Dock = DockStyle.Fill;
form.Size = new Size(30, 30);
form.BackgroundImageLayout = ImageLayout.Center;
//this.TopMost = true; // wrong! this will steal the focus!!
form.ShowInTaskbar = false;
}
// later we only show and update it..
form.Show();
form.Location = new Point(Cursor.Position.X + 5, Cursor.Position.Y + 5);
// we want the Focus to be on the main form!
Focus();
}
private void pictureBox1_MouseLeave(object sender, EventArgs e)
{
if (form!= null) form.Hide();
}

MouseHover = Occurs when the mouse pointer rests on the control. (msdn)
Try MouseMove instead.

Related

Dock Panel on Button Click C#

I'm using WinForms. In my form i have 2 panels which i want to dock up or down on button click.
The issue i'm running into is that my panels is not docking correctly.
When i click on the up button, panel one label gets covered by panel2.
Panel 1: (Anchor: Top, Left, Right)
Panel 2: (Anchor: Top, Bottom, Left, Right)
private void Up_Btn_Click(object sender, EventArgs e)
{
panel1.Dock = System.Windows.Forms.DockStyle.Fill;
panel2.Dock = System.Windows.Forms.DockStyle.Top;
}
private void Down_Btn_Click(object sender, EventArgs e)
{
panel1.Dock = System.Windows.Forms.DockStyle.Fill;
panel2.Dock = System.Windows.Forms.DockStyle.Bottom;
}
Incorrect the label should not be covered by the panels
What supposed to happen when Up button is clicked
What supposed to happen when Down button is clicked
public Form1()
{
InitializeComponent();
panel1.BringToFront();
}
private void Up_Click(object sender, EventArgs e)
{
panel1.Dock = DockStyle.Fill;
panel2.Dock = DockStyle.Top;
}
private void Down_Click(object sender, EventArgs e)
{
panel1.Dock = DockStyle.Fill;
panel2.Dock = DockStyle.Bottom;
}
The trick is to correct the order of the controls.
See here: Docking multiple controls - one fills remaining space

How to make a borderless form draggable on a custom title bar? [duplicate]

This question already has answers here:
How to move and resize a form without a border?
(7 answers)
Closed 7 years ago.
I have created a border-less form using c# but could make the custom title bar movable so I search the internet and found this code:
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == WM_NCHITTEST)
m.Result = (IntPtr)(HT_CAPTION);
}
private const int WM_NCHITTEST = 0x84;
private const int HT_CLIENT = 0x1;
private const int HT_CAPTION = 0x2;
After applying this code can click and drag my form in every inch of the form except for the title bar .
This is a good example of the movable title bar.
This is a full example
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Custom_Title_Bar
{
public partial class MainForm : Form
{
private PictureBox title = new PictureBox(); // create a PictureBox
private Label minimise = new Label(); // this doesn't even have to be a label!
private Label maximise = new Label(); // this will simulate our this.maximise box
private Label close = new Label(); // simulates the this.close box
private bool drag = false; // determine if we should be moving the form
private Point startPoint = new Point(0, 0); // also for the moving
public MainForm()
{
this.FormBorderStyle = FormBorderStyle.None;// get rid of the standard title bar
this.title.Location = this.Location; // assign the location to the form location
this.title.Width = this.Width; // make it the same width as the form
this.title.Height = 50; // give it a default height (you may want it taller/shorter)
this.title.BackColor = Color.Black; // give it a default colour (or load an image)
this.Controls.Add(this.title); // add it to the form's controls, so it gets displayed
// if you have an image to display, you can load it, instead of assigning a bg colour
// this.title.Image = new Bitmap(System.Environment.CurrentDirectory + "\\title.jpg");
// if you displayed an image, alter the SizeMode to get it to display as you want it to
// examples:
// this.title.SizeMode = PictureBoxSizeMode.StretchImage;
// this.title.SizeMode = PictureBoxSizeMode.CenterImage;
// this.title.SizeMode = PictureBoxSizeMode.Zoom;
// etc
// you may want to use PictureBoxes and display images
// or use buttons, there are many alternatives. This is a mere example.
this.minimise.Text = "Minimise"; // Doesn't have to be
this.minimise.Location = new Point(this.Location.X + 5, this.Location.Y + 5); // give it a default location
this.minimise.ForeColor = Color.Red; // Give it a colour that will make it stand out
// this is why I didn't use an image, just to keep things simple:
this.minimise.BackColor = Color.Black; // make it the same as the PictureBox
this.Controls.Add(this.minimise); // add it to the form's controls
this.minimise.BringToFront(); // bring it to the front, to display it above the picture box
this.maximise.Text = "Maximise";
// remember to make sure it's far enough away so as not to overlap our minimise option
this.maximise.Location = new Point(this.Location.X + 60, this.Location.Y + 5);
this.maximise.ForeColor = Color.Red;
this.maximise.BackColor = Color.Black; // remember, we want it to match the background
this.maximise.Width = 50;
this.Controls.Add(this.maximise); // add it to the form
this.maximise.BringToFront();
this.close.Text = "Close";
this.close.Location = new Point(this.Location.X + 120, this.Location.Y + 5);
this.close.ForeColor = Color.Red;
this.close.BackColor = Color.Black;
this.close.Width = 37; // this is just to make it fit nicely
this.Controls.Add(this.close);
this.close.BringToFront();
// now we need to add some functionality. First off, let's give those labels
// MouseHover and MouseLeave events, so they change colour
// Since they're all going to change to the same colour, we can give them the same
// event handler, which saves time of writing out all those extra functions
this.minimise.MouseEnter += new EventHandler(Control_MouseEnter);
this.maximise.MouseEnter += new EventHandler(Control_MouseEnter);
this.close.MouseEnter += new EventHandler(Control_MouseEnter);
// and we need to do the same for MouseLeave events, to change it back
this.minimise.MouseLeave += new EventHandler(Control_MouseLeave);
this.maximise.MouseLeave += new EventHandler(Control_MouseLeave);
this.close.MouseLeave += new EventHandler(Control_MouseLeave);
// and lastly, for these controls, we need to add some functionality
this.minimise.MouseClick += new MouseEventHandler(Control_MouseClick);
this.maximise.MouseClick += new MouseEventHandler(Control_MouseClick);
this.close.MouseClick += new MouseEventHandler(Control_MouseClick);
// finally, wouldn't it be nice to get some moveability on this control?
this.title.MouseDown += new MouseEventHandler(Title_MouseDown);
this.title.MouseUp += new MouseEventHandler(Title_MouseUp);
this.title.MouseMove += new MouseEventHandler(Title_MouseMove);
}
private void Control_MouseEnter(object sender, EventArgs e)
{
if (sender.Equals(this.close))
this.close.ForeColor = Color.White;
else if (sender.Equals(this.maximise))
this.maximise.ForeColor = Color.White;
else // it's the minimize label
this.minimise.ForeColor = Color.White;
}
private void Control_MouseLeave(object sender, EventArgs e)
{
// return them to their default colors
if (sender.Equals(this.close))
this.close.ForeColor = Color.Red;
else if (sender.Equals(this.maximise))
this.maximise.ForeColor = Color.Red;
else // it's the minimise label
this.minimise.ForeColor = Color.Red;
}
private void Control_MouseClick(object sender, MouseEventArgs e)
{
if (sender.Equals(this.close))
this.Close(); // close the form
else if (sender.Equals(this.maximise))
{
// maximise is more interesting. We need to give it different functionality,
// depending on the window state (Maximise/Restore)
if (this.maximise.Text == "Maximise")
{
this.WindowState = FormWindowState.Maximized; // maximise the form
this.maximise.Text = "Restore"; // change the text
this.title.Width = this.Width; // stretch the title bar
}
else // we need to restore
{
this.WindowState = FormWindowState.Normal;
this.maximise.Text = "Maximise";
}
}
else // it's the minimise label
this.WindowState = FormWindowState.Minimized; // minimise the form
}
void Title_MouseUp(object sender, MouseEventArgs e)
{
this.drag = false;
}
void Title_MouseDown(object sender, MouseEventArgs e)
{
this.startPoint = e.Location;
this.drag = true;
}
void Title_MouseMove(object sender, MouseEventArgs e)
{
if (this.drag)
{
// if we should be dragging it, we need to figure out some movement
Point p1 = new Point(e.X, e.Y);
Point p2 = this.PointToScreen(p1);
Point p3 = new Point(p2.X - this.startPoint.X,
p2.Y - this.startPoint.Y);
this.Location = p3;
}
}
} // end of the class
} // end of the namespace
If you want you can extract just the moving code and integrate it with your code, the movable Title code is just in the following Event Handlers
Title_MouseUp
Title_MouseDown
Title_MouseMove
Here is the original article for this code, you can read it for more explanation about the code
http://www.dreamincode.net/forums/topic/64981-designing-a-custom-title-bar/
The link to original article is broken

Use image Button with transparent color area

I have a picture in PNG with transparent and normal color.
I use this for one Button:
this.Button1.BackColor = System.Drawing.Color.Transparent;
this.Button1.BackgroundImage = Image;
this.Button1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
this.Button1.FlatAppearance.BorderSize = 0;
this.Button1.FlatAppearance.MouseDownBackColor = System.Drawing.Color.Transparent;
this.Button1.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent;
this.Button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.Button1.Location = new System.Drawing.Point(0, 0);
this.Button1.Margin = new System.Windows.Forms.Padding(0);
this.Button1.Name = "Skin";
this.Button1.Size = new System.Drawing.Size(294, 194);
this.Button1.TabIndex = 7;
this.Button1.UseVisualStyleBackColor = false;
And I when I click at transparent area, it still counts as a click on the Button.
How can I make this Button only call click event when I click at the colored area?
And when I click at the transparent area, I want it to count as a click on the object behind this button.
You have two options:
Use a Button with a Region.
Use a Button with a BackgroundImage and check what the user hits with each Click
Option one is only feasible if you can create a Region, which takes a GraphicsPath, which means that you need to create the shape you need from the Graphics primitves like lines and curves etc..
If you only have a Bitmap with transparency, you are better off not using a Button with a Region.
Instead you can use your Button1 and on every click you check the transparency of the clicked pixel.
If it is transparent you call the click event of the control below it..
private void Button1_MouseClick(object sender, MouseEventArgs e)
{
Size r = Button1.BackgroundImage.Size;
// check that we have hit the image and hit a non-transparent pixel
if ((e.X < r.Width && e.Y < r.Height) &&
((Bitmap)Button1.BackgroundImage).GetPixel(e.X, e.Y).A != 0)
{
Console.WriteLine("BUTTON clicked"); // test
// do or call your click actions here!
}
// else pass the click on..
else
{
// create a valid MouseEventArgs
MouseEventArgs ee = new MouseEventArgs(e.Button, e.Clicks,
e.X + Button1.Left, e.Y + Button1.Top, e.Delta);
// pass it on to the stuff below us
pictureBox1_MouseClick(pictureBox1, ee);
Console.WriteLine("BUTTON NOT clicked"); // test
}
}
Note that the check assumes that you have a normal layout, with the button image at the top left and no scaling. If you need to scale the image you should keep a scaled bitmap to do the checks on.. But if you can use an unscale image you should do so, as this will look better.
Note how I create a correct MouseEventArgs parameter for the control below, so you can access the button or the location of the mouse there as well..
Also note that it is easier to use the MouseClick event instead of the Click event as it has the mouse location already..
If you need/want to use the Click event instead, you can skip creating the EventArgs, as it doesn't have meaningful data; just pass out the e from the click..
Here is how the Click event could start:
private void Button1_Click(object sender, EventArgs e)
{
// we need the location of the clicked pixel:
Point clickLocation = Button1.PointToClient(Control.MousePosition);
// the rest can proceed as above, just with simple EventArgs..
If you want to the check on all mouse clicking event and pass each of them down to the parent you will have to code them all.
First let's look at the order of events on MSDN
MouseDown event.
Click event.
MouseClick
MouseUp event.
So we need to start at the MouseDown. We can do the test in a helper function hitTest, so we can re-use it..:
Button clickedButton = null;
MouseEventArgs ee = null;
void hitTest(Button btn, MouseEventArgs e)
{
Size r = btn.BackgroundImage.Size;
// check that we have hit the image and hit a non-transparent pixel
if ((e.X < r.Width && e.Y < r.Height) &&
((Bitmap)btn.BackgroundImage).GetPixel(e.X, e.Y).A != 0)
{
clickedButton = btn;
ee = new MouseEventArgs(e.Button, e.Clicks, e.X + btn.Left, e.Y + btn.Top, e.Delta);
}
else clickedButton = null;
}
Now we code all four events. We need to call hitTest only once and we pass the simple, unmodified e parameter in the Click event:
private void Button1_MouseDown(object sender, MouseEventArgs e)
{
hitTest(sender as Button, e);
if (sender != clickedButton)
yourParent_MouseDown((sender as Button).Parent, ee);
else // do your stuff
}
private void Button1_Click(object sender, EventArgs e)
{
if (sender != clickedButton)
yourParent_Click((sender as Button).Parent, e);
else // do your stuff
}
private void Button1_MouseClick(object sender, MouseEventArgs e)
{
if (sender != clickedButton)
yourParent_MouseClick((sender as Button).Parent, ee);
else // do your stuff
}
private void Button1_MouseUp(object sender, MouseEventArgs e)
{
if (sender != clickedButton)
yourParent_MouseUp((sender as Button).Parent, ee);
else // do your stuff
}
Of course you need to code all four events for yourParent also..

C# - Drag and Drop & Keep Control

So I am trying to make a drag and drop application that drags something on a panel. I did it before and I have forgot the code that I used for it. I would also like it to have an event too. Here is an example that failed to work:
private void pictureBox1_Click(object sender, EventArgs e)
{
PictureBox flower1 = new PictureBox();
flower1.Image = pictureBox1.Image;
flower1.Location = new Point(panel1.Location.X, panel1.Location.Y);
flower1.Width = 100;
this.Controls.Add(flower1);
flower1.MouseDown += new MouseEventHandler(flower1_MouseDown);
}
void flower1_MouseDown(object sender, MouseEventArgs e)
{
//flower1.Location = new Point(MousePosition.X, MousePosition.Y);
}
I wanted me to click on a flower, then it would be placed onto the panel then, if the mouse is clicked over that control duplicated onto the panel, then make the location the mouse cursors location. How would I go about doing any of this? It does not even appear to duplicate.
EDIT: Just realised that the image is underneath the panel making it not able to be seen. That's one issue, now how do I get it to drag and drop?
private void pictureBox1_Click(object sender, EventArgs e)
{
PictureBox flower1 = new PictureBox();
flower1.Image = pictureBox1.Image;
flower1.Location = Point.Empty;
flower1.Width = 100;
flower1.Parent = panel1;
flower1.MouseDown += new MouseEventHandler(flower1_MouseDown);
}

How to do a background for a label will be without color?

I want to add a label to my form , and I want it without any color- I want just it's text to be visible, I don't find this option in the label's properties, can anyone help me please?
Do you want to make the label (except for the text) transparent? Windows Forms (I assume WinForms - is this true) doesn't really support transparency. The easiest way, sometimes, is Label's Backcolor to Transparent.
label1.BackColor = System.Drawing.Color.Transparent;
You will run into problems though, as WinForms really doesn't properly support transparency. Otherwise, see here:
http://www.doogal.co.uk/transparent.php
http://www.codeproject.com/KB/dotnet/transparent_controls_net.aspx
http://www.daniweb.com/code/snippet216425.html
Setting the parent of a usercontrol prevents it from being transparent
Good luck!
If you picture box in the background then use this:
label1.Parent = pictureBox1;
label1.BackColor = Color.Transparent;
Put this code below InitializeComponent(); or in Form_Load Method.
Ref: https://www.c-sharpcorner.com/blogs/how-to-make-a-transparent-label-over-a-picturebox1
You are right. but here is the simplest way for making the back color of the label transparent
In the properties window of that label select Web.. In Web select Transparent
:)
this.label1.BackColor = System.Drawing.Color.Transparent;
Let's view 2 possible cases.
Background is a color.
Double-Click the form background in VS constructor. Then, write this code:
/*
This code will set all your object's background color to the same as the form.
This should be written in the body of <FormName>_Load(object, EventArgs).
*/
Control[] objs = new Control[] { /* your object list, e. g { myLabel, myPicture } */ };
foreach (Control control in objs) {
control.BackColor = Color.Transparent;
// OR
control.BackColor = this.BackColor;
}
Background is a PictureBox.
This is also easy. We just need to make all objects as children of your PictureBox and set it's color to transparent. Code:
/*
This code will set all your object's background to transparent and show the PBox.
This should be written in the body of <FormName>_Load(object, EventArgs)'s foreach loop.
Put everything before it the same as in 1st code fragment.
*/
control.Parent = back;
control.BackColor = Color.Transparent;
Let's see the pictures.
Color
Before
After
PictureBox
Before
After (here foreground were changed, don't mind this)
Generally, labels and textboxes that appear in front of an image is best organized in a panel. When rendering, if labels need to be transparent to an image within the panel, you can switch to image as parent of labels in Form initiation like this:
var oldParent = panel1;
var newParent = pictureBox1;
foreach (var label in oldParent.Controls.OfType<Label>())
{
label.Location = newParent.PointToClient(label.Parent.PointToScreen(label.Location));
label.Parent = newParent;
label.BackColor = Color.Transparent;
}
This uses Graphics.CopyFromScreen so the control needs to be added when it's visable on screen.
public partial class TransparentLabelControl : Label
{
public TransparentLabelControl()
{
this.AutoSize = true;
this.Visible = false;
this.ImageAlign = ContentAlignment.TopLeft;
this.Visible = true;
this.Resize += TransparentLabelControl_Resize;
this.LocationChanged += TransparentLabelControl_LocationChanged;
this.TextChanged += TransparentLabelControl_TextChanged;
this.ParentChanged += TransparentLabelControl_ParentChanged;
}
#region Events
private void TransparentLabelControl_ParentChanged(object sender, EventArgs e)
{
SetTransparent();
if (this.Parent != null)
{
this.Parent.ControlAdded += Parent_ControlAdded;
this.Parent.ControlRemoved += Parent_ControlRemoved;
}
}
private void Parent_ControlRemoved(object sender, ControlEventArgs e)
{
SetTransparent();
}
private void Parent_ControlAdded(object sender, ControlEventArgs e)
{
if (this.Bounds.IntersectsWith(e.Control.Bounds))
{
SetTransparent();
}
}
private void TransparentLabelControl_TextChanged(object sender, EventArgs e)
{
SetTransparent();
}
private void TransparentLabelControl_LocationChanged(object sender, EventArgs e)
{
SetTransparent();
}
private void TransparentLabelControl_Resize(object sender, EventArgs e)
{
SetTransparent();
}
#endregion
public void SetTransparent()
{
if (this.Parent!= null)
{
this.Visible = false;
this.Image = this.takeComponentScreenShot(this.Parent);
this.Visible = true;
}
}
private Bitmap takeComponentScreenShot(Control control)
{
Rectangle rect = control.RectangleToScreen(this.Bounds);
if (rect.Width == 0 || rect.Height == 0)
{
return null;
}
Bitmap bmp = new Bitmap(rect.Width, rect.Height, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(bmp);
g.CopyFromScreen(rect.Left, rect.Top, 0, 0, bmp.Size, CopyPixelOperation.SourceCopy);
return bmp;
}
}
An easy way to have a label with a picture behind it is to use the Image Property of the label itself. This will print the text over the top of the picture, and enable you to align the image (top/bottom/left/right/centre) as required.picture

Categories

Resources