首页 > 解决方案 > 通过循环在表单上添加标签

问题描述

我试图通过 powershell 在窗体上绘制 Windows 徽标。以下代码将只在表单上放置一个点。它出什么问题了?

 $labels = @(0)*5
   for ($i=0;$i -lt 4;$i++)
     { $labels[$i] = new-object system.window.forms.label
$labels[$i].location = new-object system.drawing.point($i+10,5)
  $labels[$i].text = $i.tostring()
$main_form.controls.add($labels[$i])
}
}
   $main_form.showdialog()

输出只是表格上的一个点。将文本值更改为“a”仅打印一个 a。

标签: powershell

解决方案


您的 x 和 y 坐标以错误的方式出现 -使用then ,但是您将所有控件放在同一个Controls.Add坐标上,并且每个控件的 x 偏移量为 1 个像素(您可能是指而不是),所以它们'都相互重叠。xyy$i * 10$i + 10

还有一堆拼写错误 - 例如system.window.forms-window而不是windows,new-object system.drawing.point($i+10,5)甚至不起作用(它给出了Method invocation failed because [System.Object[]] does not contain a method named 'op_Addition'.错误)。在提交之前花一些时间测试您发布的代码是值得的,甚至可以从您的问题中剪切和粘贴它以确保它实际运行,因为您更有可能得到某人的回复!

无论如何,以下内容对我有用:

Add-Type -AssemblyName "System.Windows.Forms";
Add-Type -AssemblyName "System.Drawing";

$main_form = new-object System.Windows.Forms.Form;

$labels = @();
for( $i=0; $i -lt 5; $i++ )
{

    $label = new-object System.Windows.Forms.Label;

    $label.BackColor = "Orange";
    $label.Location = new-object System.Drawing.Point(10, ($i * 25));
    $label.Text = $i.ToString();

    $labels += $label;
    $main_form.Controls.Add($label);

}

$main_form.ShowDialog();

它显示了这样的形式:

在此处输入图像描述

随意调整它以满足您的需求。


推荐阅读