我的表格中有一张较小的图片。当用户将鼠标悬停在图像上时,它会显示更大的图像视图(跟随鼠标,但与鼠标保持一定距离)。为了做到这一点,我在光标悬停图像时生成一个没有FormBorderStyles的Form。
我遇到的问题是,一旦表单激活,第一个表单似乎不再检测到鼠标悬停或离开PictureBox。表格也不跟随光标。
这是我所得到的精简版:
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");
}
}
答案 0 :(得分:2)
MouseLeave
(以及其他事件)无法识别,因为弹出窗口的打开,特别是使其topmost=true
从原始表单及其PictureBox
中删除焦点。 / p>
它也没有移动,因为没有提供移动代码..
以下是一些将使表单移动的更改:
form1
级MouseMove
活动请注意,Hover
是一次性事件。它只会触发一次直到您离开控件..(注意:Setsu已从Hover
切换到Enter
。这样可以正常工作,但在显示第二个之前没有短暂的延迟表格。如果你想要回来,你可以切换回Hover
,或者你可以用Timer
伪造悬停延迟,这是我经常做的。)
// 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();
}
答案 1 :(得分:0)
MouseHover =鼠标指针停留在控件上时发生。 (msdn)
尝试使用MouseMove。