是否可以在c#中传播同一表单的多个实例? 说我有这个代码:
for (int i = 0; i < 10; i++)
{
Form myForm = new Form();
myForm.Show();
}
我想在随机位置在屏幕上传播这10个窗口。我该怎么做?请回复一些我可以使用的代码。谢谢!
答案 0 :(得分:0)
您需要一个像Random
这样的随机生成器并设置窗口的Location
:
Random random = new Random();
for (int i=0; i<10; i++)
{
Form myform = new Form();
int x = random.Next(0, Screen.PrimaryScreen.Bounds.Width);
int y = random.Next(0, Screen.PrimaryScreen.Bounds.Height);
myForm.Location = new Point(x, y);
myForm.Show();
}
注意事项:
Random
实例化为循环,否则您总是会获得具有相同种子的新实例,从而导致始终保持相同的位置Screen.PrimaryScreen
是否适合您,或者您是否需要处理多个屏幕(这将是一个额外的主题)Width
和Height
中减去一些内容,否则你可能会在屏幕的右上方或下方显示左上角的窗口:示例:
int x = random.Next(0, Screen.PrimaryScreen.Bounds.Width - myForm.Width);
int y = random.Next(0, Screen.PrimaryScreen.Bounds.Height - myForm.Height);