Home > Software design >  C# Windows Forms - Invisible Element with Events (Click and MouseEnter/Leave)
C# Windows Forms - Invisible Element with Events (Click and MouseEnter/Leave)

Time:11-17

I have arranged several labels directly next to each other in my project. Now I would like to execute events like Click or MouseEnter/Leave when I am approximately on the edge between them. I tried to put an invisible element at this position and catch the events from this element, but as soon as I make the element invisible the events don't work anymore.

I want this not only for the edges between 2 labels, but also at the corners for up to 4 labels docking at this corner.

The important thing is that I need to know at the event which edge or corner it is and which labels dock to it respectively.

I have attached an image to better visualize this. The highlighted places are just examples where I would like to catch these events. But it should be possible at any edge and corner between the labels.

enter image description here

CodePudding user response:

Maybe one option is to paint border of the label yourself, then you don't need to place element inbetween.

private void label3_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.DrawRectangle(new Pen(new SolidBrush(Color.Red), 10f), label3.ClientRectangle);
    base.OnPaint(e);
}

So if you add a Paint Event on the label then you can draw the border (here in red with a width of 10). The border is treated as a part of the label, so all events performed on the border will be triggered in the same way,

CodePudding user response:

One way to achieve this is to add a label as the background which you can set to the same colour as the form background which would make it appear hidden.

You can then attach the click, enter and leave events to that label which will trigger as soon as you move the mouse cursor of one of your other labels onto your background label.

I've mocked up this screen, with the background label a darker colour so you can see: enter image description here

I've named the dark background 'lblBackdrop' and the textbox below 'txtMessage'.

Then I attached the following handlers to the background label:

using System;
using System.Windows.Forms;

namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void lblBackdrop_Click(object sender, EventArgs e)
        {
            txtMessage.Text = string.Concat(txtMessage.Text, "Background clicked\n");
        }

        private void lblBackdrop_MouseLeave(object sender, EventArgs e)
        {           
            txtMessage.Text = string.Concat(txtMessage.Text, "Background left\n");
        }

        private void lblBackdrop_MouseEnter(object sender, EventArgs e)
        {
            txtMessage.Text = string.Concat(txtMessage.Text, "Background entered\n");
        }
    }
}
  • Related