管理位置 [英] managing the location
问题描述
假设我有主要来自和按钮。我有另一个Form form2,当我点击主窗体的按钮,我希望窗体2出现在按钮下方。无论我在哪里保留按钮和我保持主窗体的位置,即拖动到任何角落..
suppose i have main from and button in it. and i have another Form form2, when i click in the button of the main form i want Form 2 appear just below the button. No matter where i kept the button and where i kept the main form i.e. drag to any corner..
推荐答案
获取按钮在其事件处理程序中的位置并将其传递给像这样的自定义构造函数:(未经测试)
Get the button's location in its event handler and pass it to a custom constructor like this: (untested)
private void button1_Click(object sender, EventArgs e)
{
Button source = sender as Button;
if (source == null)
{
return;
}
Point lowerLeft = source.PointToScreen(new Point(0, source.Height));
Form2 child = new Form2(lowerLeft);
child.ShowDialog();
}
class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public Form2(Point location) : this()
{
this.Location = location;
}
}
并设置From2的 StartPosition [ ^ ]属性为 Manual [ ^ ]。
[/编辑]
And set From2's StartPosition[^] property to Manual[^].
[/Edit]
您好thedinesh01,
我想出了与lukeer相同的解决方案(但我认为不需要为Form2创建一个特殊的构造函数。看起来你还有问题。所以也许你试一试:
Hi thedinesh01,
I came up with the same solution as lukeer (but I don't see a need to create a special constructor for Form2). It looks you still have problems. So maybe you give it a try:
using System;
using System.Drawing;
using System.Windows.Forms;
namespace SetFormLocation
{
class Program
{
static void Main(string[] args)
{
Form formMain = new Form();
Button buttonOpenDialog = new Button { Text = "Open", Location = new Point(20, 20), Parent = formMain };
buttonOpenDialog.Click += (object objSender, EventArgs ea) =>
{
Button buttonSender = objSender as Button;
if(buttonSender == null ) return;
Point ptLocation = buttonSender.PointToScreen(new Point(0, buttonSender.Height));
Form dialog = new Form { StartPosition = FormStartPosition.Manual, DesktopLocation = ptLocation };
dialog.ShowDialog(formMain);
};
Application.Run(formMain);
}
}
}
(创建一个新的Forms项目并替换生成的程序。 cs文件的内容与上面的代码)。
涉及的步骤是:
设置 StartPosition
到 FormStartPosition.Manual
获取按钮的屏幕坐标(使用 PointToScreen
)
将所需的偏移量添加到找到的屏幕坐标(在您的情况下是按钮高度)
设置 DesktopLocation
(或位置
)您的对话框在屏幕坐标中显示所需的值。
应该简单易用跨越多个监视器等(我也测试了代码)
亲切的问候Johannes
(Create a new Forms project and replace the generated Program.cs file's content with the above code).
Steps involved are:
Set StartPosition
to FormStartPosition.Manual
Get the Screen coordinates for your button (with PointToScreen
)
Add the desired offset to the found screen coordinates (in your case the button hight)
Set DesktopLocation
(or Location
) for your dialog to the desired value in screen-coordinates.
Should be realy simple and works across multiple monitors etc. (I tested the code too)
Kind regards Johannes
这篇关于管理位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!