Quantcast
Channel: PowerShell General
Viewing all articles
Browse latest Browse all 10624

Functions of Functions

$
0
0

Sorry my terminology may be off as I'm learning still!

I'm writing code where I am going to reuse chunks of code in my script so want to make them into functions.

For example I can now easily add labels onto my forms by adding a function of:

# This Function Generates a label
function Label ($text="Default Label Text", $position_vertical=10, $position_horizontal=10, $width=100, $height=20) {
 $objLabel = New-Object System.Windows.Forms.Label
 $objLabel.Text = "$text" + ":"
 $objLabel.Location = New-Object System.Drawing.Size($position_horizontal,$position_vertical)
 $objLabel.Size = New-Object System.Drawing.Size($width,$height)
 $Form.Controls.Add($objLabel)
}

Then I can call this code time and again with the line (for example):

#Add a First Name text box.
Label -text "First Name" -position_vertical 40

This works nicely with the parameters having defaults so you only have to declare none standard ones.

My question is how would I do the same for a text box (and other form elements)? I can see the problem being that I need to vary a variable name! I somehow need to collect the output of the text box. I suspect I need to reference some Controls?

I tried to get round this with:

# This Function Generates a Textbox
function Textbox ($name="Default_Textbox", $position_vertical=10, $position_horizontal=120, $width=100, $height=20) {
 $objTextBox_$name = New-Object System.Windows.Forms.TextBox
 $objTextBox_$name.Location = New-Object System.Drawing.Size($position_horizontal,$position_vertical)
 $objTextBox_$name.Size = New-Object System.Drawing.Size($width,$height)
 $Form.Controls.Add($objTextBox_$name)
}

...but that would be way too easy and is blatently wrong. Can someone point me in the right direction.


Viewing all articles
Browse latest Browse all 10624

Trending Articles