问题描述
当我运行我的程序时,会出现两个表单。
Form1和Form2。
现在我需要的是将form1的位置移动到屏幕的任何位置通过鼠标,form2移动到form1去的地方。
我的意思是我需要Form2才能锁定Form1。
如何????
谢谢。
When I run my program, two forms comes up.
Form1 and Form2.
Now what I need is when I move the placement of form1 to anywhere of screen via mouse, form2 moves where ever form1 goes.
I mean I need Form2 to be lock on Form1.
How????
Thanks.
推荐答案
using System;
using System.Drawing;
using System.Windows.Forms;
namespace YourNameSpace
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Form2 f2 = new Form2();
private void Form1_Load(object sender, EventArgs e)
{
f2.Show();
// the Form2 instance will use the same EventHandlers
// that the Form1 instance (Main Form) uses
f2.LocationChanged += Form1_SizeAndLocationChanged;
f2.SizeChanged += Form1_SizeAndLocationChanged;
// need to adjust the position on Application start
// note: you could just as well call this with
// both arguments being 'null
Form1_SizeAndLocationChanged(sender, e);
}
// convenience method
private void PositionForm2(int fLeft, int fTop)
{
f2.Location = new Point(fLeft, fTop);
}
// Both the Form1 instance LocationChanged,
// and SizeChanged Events use this EventHandler
private void Form1_SizeAndLocationChanged(object sender, EventArgs e)
{
// experiment using one of these method calls
// Form2 left, top docked Form1 right, top
PositionForm2(this.Right, this.Top);
// Form2 right, top docked Form1 left, top
//PositionForm2(this.Left - f2.Width, this.Top);
// Form2 left, top docked Form1 right, Bottom
// PositionForm2(this.Right, this.Bottom);
// Form2 right, top docked Form1 left, bottom
//PositionForm2(this.Left - f2.Width, this.Bottom);
}
// try experimenting with this with the code in
// Form1_SizeAndLocationChanged commented out
// and observe the differences
//private void Form1_MouseMove(object sender, MouseEventArgs e)
//{
//Form1_SizeAndLocationChanged(sender, e);
//}
}
}
讨论:
1。此代码要求您在设计时将Form1 LocationChanged和SizeChanged事件的EventHandlers分配给Form1_SizeAndLocationChanged方法。
2.显示的简单示例存在一些问题这里应该解决生产质量代码:
a。如果目标是从不将Form2的任何部分移出屏幕边界怎么办?
b。如果Form1被最小化或最大化会发生什么?
Discussion:
1. This code requires you assign at design-time the EventHandlers for both Form1 LocationChanged and SizeChanged Events to the Form1_SizeAndLocationChanged method.
2. There are some issues with the simple example shown here that should be addressed for production quality code:
a. What if the goal is to never have any part of Form2 moved outside the Screen boundaries ?
b. What should happen if Form1 is Minimized, or Maximized ?
这篇关于Lock Form1& Form2在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!