Building Forms with PowerShell – Part 1 (The Form)

时间:2023-01-08 07:34:07

For those of you familiar with Scripting languages you are probably used to using alternate applications like Visual Studio when you want to create GUIs for your scripts.

There are a handful of other utilities for PowerShell too, which are a little cheaper to buy and still have the benefit of speeding up things like creating a GUI for your PowerShell script and Forms etcetera.

Rather than spending money and having to learn how to use an additional tool, if you do not mind a little extra finger work, you can code your own GUI and Forms in PowerShell, and if you want you can even make use of Extensible Application Markup Language (XAML) language, and a handful of similar templates to help speed things up.

Right now though, all that is more advanced, and beyond the focus of this introduction to creating a Form. Later, in other Tutorials I'll cover these advanced techniques, but for now let's get on with the basics.

As PowerShell is centered around the .Net Framework you can make use of the [System.Windows.Forms] assembly to create a new object System.Windows.Forms.Form.

As the [System.Windows.Forms] assembly is does not automatically load in PowerShell you need to add this assembly yourself by using the cmdlet Add-Type and the -AssemblyName parameter, then having done this create your new object.

Note: You can also load the assembly using the following command:

Code (PowerShell):
[reflection.assembly]::LoadWithPartialName("System.Windows.Forms")

Let's take a look at the simpler (and easier to remember) method combined with a basic script:

Code (PowerShell):
# Load the System.Windows.Forms assembly into PowerShell
Add-Type -AssemblyName System.Windows.Forms

# Create a new Form object and assign to the variable $Form
$Form = New-Object System.Windows.Forms.Form

#Initialize Form so it can be seen
$Form.showDialog()
 

If we open PowerShell or PowerShell ISE and run this basic script the following GUI form is generated:

Building Forms with PowerShell – Part 1 (The Form)

Obviously, this form is of no practical use to us yet, but it is a platform we can use to start creating a more useful Form.

Take a look at the following code block:

Code (PowerShell):
# Add description to the Form's titlebar
$Form.Text = "The Titlebar - Form"

# Create a new Label object
$Label = New-Object System.Windows.Forms.Label

# Add some text to label
$Label.Text = "Some random text to display"

# Use AutoSize to guarantee label is correct size to contain text we add
$Label.AutoSize = $true

# Add Label to form
$Form.Controls.Add($Label)

We can add this to our original Script to add a description to our Form's Title bar, and also add a new dimension to the form: the Label object, which we can use to add some text into the form.

Building Forms with PowerShell – Part 1 (The Form)

  • By using the .Text method with out $Form variable we are able to add a description to the Form's title bar.
  • We can create a new element in our form; the Label using the New-Object cmdlet to introduce the System.Windows.Forms.Labeland this can be assigned to a variable.
  • Once we have assigned the Label to a variable we can then use the .Text method to add text to the label.
  • Given the text we add might be short or very long, its a good idea to make use of the AutoSize method to guarantee the label is large enough to hold whatever text we choose to enter for the label.
  • Now all you need to do is add the Label to our current Form using the Controls.add(<variable>).
  • The rest of the script is the initial building block you previously created.

Starting to be a more useful form now, but for the fact the default font size is not too great for those of us who need glasses to read it, and do you actually like the font face, what if you want something a little different; perhaps to make the form a little nicer, or perhaps because a certain font face is easier to read for you.

Not a problem, we can continue building on our code by adding some additional commands. For example:

Code (PowerShell):
# Choose a font face, font size, and style
# Other styles include Bold, Italic, Underline and Strikeout
# Note:  Fontface must be present on users computer
$FontFace = New-Object System.Drawing.Font(
  "Comic Sans MS",20,[System.Drawing.FontStyle]::Regular
)

# Initialize the forms font
$Form.Font = $FontFace

# AutoSize ensures the Form size can contain the text
$Form.AutoSize = $true

# Allow user to resize too vs "GrowAndShrink" - user cannot resize
$Form.AutoSizeMode = "GrowOnly"

Now if we add this to our building block we get:

Building Forms with PowerShell – Part 1 (The Form)

  • This introduces a little more finger work!
  • First we need to create a new variable to store our Font information. You can call that variable whatever you like. Then you need to assign a new object to it which allows you to introduce System.Windows.Font(<Name>,<Size>,<Style>)
  • We then need to initialize our Forms font by assigning our new object to our $Form.Font(<object>)
  • As we are using a large font size, we include the AutoSize() for $Form to ensure the form automatically sizes to hold our text message in an easy to read format: $Form.AutoSize = $true
  • In addition I've added an additional option AutoSizeMode (which is not compulsory), but allows the Form to increase in size using an aspect ratio, e.g. Width x Depth: $Form.AutoSizeMode = "GrowOnly". You can control the Form size by adjusting its width only, by using "GrowAndShrink" instead.

    Using GrowAndShrink with above code would result in:

    Building Forms with PowerShell – Part 1 (The Form)

Apart from controlling these aspects of the Form, one can also take control of the Caption (i.e. Minimize, Maximize & Close buttons), as well as hide or show the SizeGrip which is what allows a user to adjust the size of the active window by dragging the bottom right corner. You can also control the opacity of the Form (i.e. whether you can see other windows beneath it and to what degree), and also determine what position on the Screen the Form will open to when activated. You can also control whether or not the activated Form will have an icon appear on the taskbar.

To achieve all this we'll need to continue building on our Script code by adding some additional blocks of code, like below:

Code (PowerShell):
# Set Form State by controlling Window settings
# Windows setting options: Minimized, Normal or Maximized
# $false disables a particular Caption choice for the user
$Form.MinimizeBox = $false
$Form.MaximizeBox = $false
$Form.WindowsState = "Normal"

# Set whether user can see Form icon in taskbar
# $false = not seen, $true = seen
$Form.ShowInTaskbar = $false

# Set whether user has access to the Size Grip for window
# Options include Auto, Hide or Show
$Form.SizeGripStyle = "Show"

# Set what position Form opens in on users screen
# Choices include:
# CenterScreen, Manual, WindowsDefaultLocation,
# WindowsDefaultBounds, CenterParent
$Form.StartPosition = "CenterParent"

# Set the opacity level for window, i.e. how transparent it is
# Range is from 0.0 (invisible) to 1.0 (100% opaque)
$Form.Opacity = 0.6

When added to our script we get:

Building Forms with PowerShell – Part 1 (The Form)

  • So in the above example by setting $Form.MinimizeBox and $Form.MaximizeBox to $false we are disabling them. If instead you assign $true to them the user will be able to use these buttons.
  • The $Form.WindowState can be assigned MinimizedNormal or Maximized which of course determines how the Form will open and display to the user.
  • In this example I set $Form.showInTaskbar to $false. This prevents the Forms icon appearing on the taskbar, but if you want that to appear there, assign $true instead.
  • The $Form.SizeGripStyle allows us to set one of three choices: Auto, Hide, or Show. By assigning Hide the grip icon normally located on the bottom right corner of our Form will not be viewed. The user can still adjust the size though, by hovering mouse to get the double-arrow.
  • The opacity can be set from 0.0 (invisible) to 1.0 which is 100% opaque (i.e. cannot be seen through)
  • The StartPosition can be one of several choices as illustrated in the code comments. In my case I used CenterParent which causes the Form to open in the top left corner, but if you wanted the Form to open in the actual center of the screen you'd go for $Form.StartPosition = "CenterScreen". Try the other choices, to determine which position you prefer. The position you settle on may in part be determined by your opacity setting.

Now for the Form background itself. We can control this too and customize its look to our person preferences. Take a look at the following code snippet:

Code (PowerShell):
# Add a background color to form
# You can use the Static color names found in System.Drawing.Color
# Static Color example: "Blue"
# Or you can use ARGB values (i.e. Alpha, Red, Green & Blue)
# by using 4 pairs of letters from A to F to represent level of
# Alpha, Red, Green & Blue in color
# ARGB example: "#FFFFABCD"
$Form5.BackColor = "#FFFFABCD"

I won't be mean and ask you to guess the colour #FFFFABCD represents.

Hint:
 think Sticky Notes.

Now add this to our script and we get:

Building Forms with PowerShell – Part 1 (The Form)

I won't go into it here, but suffice to say you could either convert this Script to an executable which you could place in your Startup folder, or create a new task to open the form at the desired time, and create your very own custom Sticky Notes.

Now you are not just stuck with pretty colours. Why not use a picture instead:

Code (PowerShell):
# Replace BackGround with an image instead
# Makes use of [System.Drawing.Image]
# This allows you to create an image Object from a file
# which can be used as a background to your form
$BackgroundPicture = [System.Drawing.Image]::FromFile(
  # Image obtained Royalty Free from https://www.pexels.com/
  "$env:UserProfile\Pictures\catface.jpg"
)

# Set the image to be used
$Form.BackgroundImage = $BackgroundPicture

# Set Layout for image
# Default = Tile which will tile the image
# inside form as many times as it will fit
# Choices include, None, Tile, Center, Stretch and Zoom
$Form.BackgroundImageLayout = "None"

# As we are using image, it is better to
# set the Form size manually to fit the image size
# Thus we do not use AutoSize (although you can if you want to)
# Instead we use Width and Height to ensure a tidy fit for image
# The cool thing is you can let the computer work that size out
$Form.Width = $BackgroundPicture.Width
$Form.Height = $BackgroundPicture.Height

As you can see in the comments of this code block, there are a number of ways to manipulate an image and the form itself to help improve the final look of a Form should you choose to use a background image.

  • Initially we create our own variable ($BackgroundPicture in my case but you can name it what you like) to store an image on our computer.
  • Next we make use of [System.Drawing.Image]::FromFile(<path to file>\<filename>) to set a path to the image.
  • You then need to assign your variable: $Form.BackgroundImage = $BackgroundPicture
  • Next you'll want to determine the layout of your image. There are several choices as mentioned in the codes comments. I've chosen $Form.BackgroundImageLayout = "None" because I will be setting the Form to size itself to my image, and thus do not need to worry about tiling, stretching, or positioning the image. 

    Note:
     If I did not choose any option here at all, the default behaviour would be for the image chosen to be tiled, hence given I do not want tiling, I had to choose an option!
  • You can set the Form's width and height to suit your image if you know the images dimensions, but rather than having to work all that out yourself, just let the computer do the work for you by using the .Width and .Height methods, e.g. $Form.Width = $BackgroundImage.Width
  • As I've introduced a background image, I need to consider the appearance of my Label which contains the text you are reading in the Form. I do not want it interfering with the image, so I set it to be transparent, by including this snippet: $Label.BackColor = "Transparent"

So after adjusting our script to include these details:

Building Forms with PowerShell – Part 1 (The Form)

And if we did not make that Label transparent we'd see:

Building Forms with PowerShell – Part 1 (The Form) 
Not so nice with a non transparent label!

Well that concludes the introduction to creating your own GUI Forms in PowerShell.

In Part 2 of this tutorial I'll take a look at how we add buttons, interactive text fields, Lists and the ability to drag and drop items into our Form.

Till then happy PowerShelling !

Regards,

Regedit32

Building Forms with PowerShell – Part 1 (The Form)的更多相关文章

  1. 在PowerShell中使用curl&lpar;Invoke-WebRequest&rpar;

    前言 习惯了windows的界面模式就很难转去命令行,甚至以命令行发家的git也涌现出各种界面tool.然而命令行真的会比界面快的多,如果你是一个码农. situation:接到需求分析bug,需要访 ...

  2. Formtastic&colon; Forms Made Crazy Easy for Rails Developers

    Formtastic is a Rails plugin by Justin French that aims to take the headaches out of building forms ...

  3. Forms in Angular 2

    Input handling is an important part of application development. The ng-model directive provided in A ...

  4. Django之Form组件

    Django之Form组件 本节内容 基本使用 form中字段和插件 自定义验证规则 动态加载数据到form中 1. 基本使用 django中的Form组件有以下几个功能: 生成HTML标签 验证用户 ...

  5. 微软准备开源PowerShell

    微软有计划在近期内开源PowerShell 近日微软再次在向开源投出橄榄枝, PowerShell是面向Windows和Windows Server的自动化平台和脚本语言,帮助用户简化系统的管理.在纳 ...

  6. powershell开源新闻及简介

    作者:PowerShll传教士 问:微软的PowerShell脚本语言已经开源了 ? 答:绝对真的!已经! 问:源码在哪? 答:微软.net源码网站.   http://referencesource ...

  7. Win Form程序线程点点

    消息循环 Win32窗体程序基于消息驱动的,程序的模型就是一个用户触发事件消息->系统分发事件消息->程序处理事件的循环过程. .NET Win Form程序对消息循环进行了封装,可以看到 ...

  8. form中的GET与POST

     form标签是强大的:如果没有form标签,Internet将变成一个枯燥文档的只读存储库.Web Forms没有完全利用form标签的强大功能(也可以说是Web Forms为实现自己的目标才管理和 ...

  9. Oracle EBS Form 发布到Server端的注意事项

    前段时间在本地XP系统上测试了一些整合javabean的Form例子,想着发布到服务器段去看看能否运行正常,一开始以为会和本地XP系统一样,部署到相关的目录下进行一些配置就可以了,但实际过程却和想象的 ...

随机推荐

  1. BZOJ4110 &colon; &lbrack;Wf2015&rsqb;Evolution in Parallel

    首先每个串都必须是$S$的子序列,否则无解. 按长度从小到大依次考虑每个串,如果它两边都不能放,那么无解. 如果能放一边,那么放进去,把待定的全部放入另一边. 如果两边都能放,那么看看能否待定,如果不 ...

  2. Javascript基础系列之(三)数据类型 (布尔型 Boolean)

    javascript同样有布尔型,可选值,true or fasle. var marr = true ; document.write(typeof(marr) + "<br> ...

  3. Leetcode&num;59 Spiral Matrix II

    原题地址 相比于Spiral Matrix(参见这篇文章)要简单一些,因为是方阵,所以代码简洁一些. 注意当n是奇数的时候,中心小块要单独赋值(代码21行) 代码: vector<vector& ...

  4. WinDBG调试&period;NET程序示例

    WinDBG调试.NET程序示例 好不容易把环境打好了,一定要试试牛刀.我创建了一个极其简单的程序(如下).让我们期待会有好的结果吧,阿门! using System; using System.Co ...

  5. koa源码之delegate使用

    koa中context可以直接调用request和response属性的重要原因是使用了delegate将req和res的属性代理到context, Delegator.prototype.gette ...

  6. &OpenCurlyDoubleQuote;Error&colon;&lpar;1&comma; 1&rpar; java&colon; 非法字符&colon; &&num;39&semi;&bsol;ufeff&&num;39&semi;”错误解决办法

    原因 用Windows记事本打开并修改.java文件保存后重新编译运行项目出现“Error:(1, 1) java: 非法字符: '\ufeff'”错误,如下图所示:     原来这是因为Window ...

  7. python下载文件的方法

    前一段时间是爬文字,最近准备爬图片 找到了两种保存文件的方法 一种是用urllib.urlretrieve方法 #-*- coding: utf-8 -*- import urllib def cal ...

  8. &lbrack;转&rsqb;C&plus;&plus; STL list的初始化、添加、遍历、插入、删除、查找、排序、释放

    list是C++标准模版库(STL,Standard Template Library)中的部分内容.实际上,list容器就是一个双向链表,可以高效地进行插入删除元素. 使用list容器之前必须加上S ...

  9. Android训练课程&lpar;Android Training&rpar; - 测试你的Android Activity

    你应该开始编写和启动测试作为你的android程序开发周期的一部分.写的好的测试能够帮助你更早的发现bug和使你对你的代码有信心. 一个测试用例定义了一些对象和方法的集合,用于启动多样的彼此独立的测试 ...

  10. UVa 230 Borrowers&lpar;map和set&rpar;

    I mean your borrowers of books - those mutilators of collections, spoilers of the symmetry of shelve ...