PrimalForms/PowerShell – Event Behavior: Tab Key or Enter Key

In this article I wanted to expand on the previous post (http://itnotes.net/2011/01/03/primalformspowershell-event-behavior-enter-key-and-active-directory-lookup/) …

Which captured the Event Behavior: KeyPress which was used to trigger an action after the Enter Key was pressed.

During a project to allow our admins to change the manager field in our AD LDS Identity Store I was coding a Textbox to be triggered with the tab key, but low and behold they TAB key is not captured by default by the KeyDown, KeyPress or KeyUp Events.

Per the Microsoft Articles:

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keydown.aspx

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keyup.aspx

Certain keys, such as the TAB, RETURN, ESC, and arrow keys are handled by controls automatically. To have these keys raise the KeyDown event, you must override the IsInputKey method in each control on your form. The code for the override of the IsInputKey would need to determine if one of the special keys is pressed and return a value of true. Instead of overriding the IsInputKey method, you can handle the PreviewKeyDown event and set the IsInputKey property to true.

Note the IsInputKey method must be set per control, so there is no need to turn it back off for other controls on the same form.

So in this example I start with a basic form with two labels, two textboxes, and a status bar to show when the TAB or ENTER keys are captured.

For the Event Behaivior: PreviewKeyDown for $textbox1 I setup the following code:

$textbox1_PreviewKeyDown=[System.Windows.Forms.PreviewKeyDownEventHandler]{
     #Event Argument: $_ = [System.Windows.Forms.PreviewKeyDownEventArgs]
     $_.IsInputKey = $true
}

For the Event Behaivor: KeyDown for $textbox1 I setup the following code:

$textbox1_KeyDown=[System.Windows.Forms.KeyEventHandler]{
#Event Argument: $_ = [System.Windows.Forms.KeyEventArgs]
      If ($_.KeyValue -eq 9) {
           $statusbar1.Text = “Tab key was pressed”
           $textbox2.Focus()
           $textbox2.Clear()
     }
     Else {$statusbar1.Text = $_.KeyValue}
}

Notes:

     1. I used the KeyDown event because the KeyPress event is not raised by noncharacter keys; however, the noncharacter keys do raise the KeyDown and KeyUp events.

     2. I use $textbox2.Focus() to move to the next control because the TAB key is no longer coded to complete that default action.

Set $textbox1 Events to the previous code sets.

To show the different between the two examples I coded $textbox2 Event Behavior: KeyPress to capture the ENTER key

$textbox2_KeyPress=[System.Windows.Forms.KeyPressEventHandler]{
#Event Argument: $_ = [System.Windows.Forms.KeyPressEventArgs]
      If ($_.KeyChar -eq 13) {
           $statusbar1.Text = “Enter Key was pressed”
           $textbox1.Focus()
           $textbox1.Clear()
     }
}

Set $textbox2 to the previous code set.

As you may have noticed in the Event to capture the TAB key we used KeyValue and in the Event to capture the ENTER key we used KeyChar.

KeyCode, KeyData or KeyValue must be used because KeyChar cannot capture the following Keys

The TAB key.

INSERT and DELETE.

HOME.

END.

PAGE UP and PAGE DOWN.

F1-F2.

ALT.

Arrow keys.

For more details about the differences between KeyCode, KeyData, and KeyValue:

http://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.keycode.aspx

http://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.keydata.aspx

http://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.keyvalue.aspx

In my next post I would like to show examples of how to use KeyChar to to control the field format of a textbox used for items like ZipCode or Telephone Numbers.

~ITNotes

PowerShell – Multiple (-and) (-or) within a single If statement

I had a hard time finding examples on the web on how or if you could code multiple If’s into a single If statement, so I thought I would just quick post up an example once I figured out how to do it. Perhaps I wasn’t looking in the right places but all the examples I saw were just a single (-and) or (-or) in the code.

So based on being able to code an If statement in either of the following fashions:

If ($someAttribute -eq $false -or $someAttribute -eq $Null){

}

or the following:

If (($someAttribute -eq $false) -or ($someAttribute -eq $Null)){

}

Then we should be able to do a combined effort:

If (($someAttribute -eq $false -or $someAttribute -eq $Null) -and ($someUser -eq “UserID123”)){
       Write-Host “Switching to True”
       Set-QADUser $someUser -Service “MyDomain.org” -ObjectAttributes @{$someAttribute = $True}
       If (!$?) {Write-Host “Error: $($error[0])”}
}

So if $someAttribute is either $false or $Null AND #someUser equalsUserID123″ then do something… in this case I switch the Attribute someAttribute to $true and do some error checking.

~ITNotes

PrimalForms/PowerShell – Event Behavior: Enter Key and Active Directory Lookup

The next event behavior I wanted to cover was hitting a Enter Key within a textbox control and have it trigger another event.

In this examble I have three basic controls a textbox,a button and a listbox.  I am using the textbox as a Search Textbox, after entering text to search the end user can either press Enter or the ‘find’ button.

First add the Event Handler for the Textbox to response only to the Enterkey.

Next add the Event Handler to search Active Directory using the text from the TextBox($txbFind) after the button($btnFind) is single clicked.

Next the code for handler_button1_Click. First the Event handler clears the listbox ($lstResults) then it searches Active Directory with the text from the Textbox ($txbFind). Then if the results if not null, the handler will list the results in the listbox($lstResults)

$handler_btnFind_Click={
$lstResults.Items.Clear()
$Users = get-qaduser $txbFind.text -service ‘MyDomain.edu’ -sizelimit 0 -includedproperties displayName | Sort displayName | select displayName
 if ($Users -ne $Null) {
  foreach ($User in $Users){
   $lstResults.Items.add($User.displayName)
  }
 }
}

Lastly we add code to the Event handler for the textbox to trigger the button($btnFind) when the Enter Key is pressed and give focus to the listbox($lstResults).

$handler_txbFind_KeyPress=[System.Windows.Forms.KeyPressEventHandler]{
If ($_.KeyChar -eq 13){
 $btnFind.PerformClick()
 $lstResults.Focus()
}
}

The results show the matching users in the listbox

Using this code I created an admin tool that modifys anything from address to exchange administration. Happy Coding!

PrimalForms/PowerShell – Event Behavior: Button Click and Switch Tab

I decided that I would post how to code a few Event Behaviors that could be coded with PowerShell using PrimalForms. You could just use your basic PowerShell Editor but PrimalForms is just my tool of choice.

So I start with a basic form (Two Tabs and a Button)

Then on the Events tab of $button1, double click ‘click’

Add the following code to the Event handler:

 $handler_button1_Click={
#TODO: Place custom script here
     If ($tabpage1.Visible -eq $true) {
          $tabcontrol1.SelectTab(‘tabpage2’)
     }
     ElseIf ($tabpage2.Visible -eq $true) {
           $tabcontrol1.SelectTab(‘tabpage1’)
     }
}

Clicking the button switches from tab to tab. Way cool!

Glimspe of the PrimalForms 2011 and PrimalScript 2011 Release?

I have been waiting impatiently for the release of PrimalForms 2011, my current project requires multi-form support so the sooner I can get my hands on this the better.

Today I found the product pages for PrimalForms 2011 and PrimalScript 2011. Neither product is listed under their current product list.

PrimalForms 2011: http://www.primaltools.com/products/primalforms2011.asp

PrimalScript 2011 http://www.primaltools.com/products/primalscript2011.asp

PowerShell – ProperCase Function

Change any case to Proper Case (‘ITNOTES DoT net’ to ‘Itnotes Dot Net’):
This is very useful for us during scripted user creations when the usernames and such from the source were in random cases. This script could also be useful with auto user provisioning with ILM/FIM 2010 from another datasource, we were using a VBScript that is much longer.

This script basically converts everything to lowercase then capitalizes the first letter of each word.

function ToProperCase ([String]$in)
{
 $in = $in.Tolower()
 $textInfo = [System.Threading.Thread]::CurrentThread.CurrentCulture.TextInfo  
 return $textInfo.ToTitleCase($in)
}

Example of use:
$Title = “ITNOTE DOT NET”
ToProperCase($Title)

Returns:
Itnotes Dot Net

Complete Script

function ToProperCase ([String]$in){
 $in = $in.Tolower()
 $textInfo = [System.Threading.Thread]::CurrentThread.CurrentCulture.TextInfo
 return $textInfo.ToTitleCase($in)
}
$Title = “ITNOTE DOT NET”
ToProperCase($Title)

As noted by Lee, here is a oneliner contributed by Jonathan Noble at http://www.jonoble.com/. Thanks Lee.

(Get-Culture).TextInfo.ToTitleCase(“THIS IS MY STRING”.ToLower())

I am always in favor of shorter scripts nevertheless I also favor functions, so here is a much shorter function:

function ToProperCase ([String]$in){
return (Get-Culture).TextInfo.ToTitleCase($in.ToLower())
}

Re-Usable VBScript Functions – Part I

In this Multi-Part Series I will post lists on VBScript Functions and Subs that I have either found or written. I am a big fan of turning any useful code into a functions and adding it to my default VBScript Template, it saves a ton of time on the next scripting task. By no means am I claiming I wrote all of  these, most were just re-purposed into reusable functions. I hope you find these useful. In the later part of the series I will include my template I use to begin all my scripts.

Determine if the computer is a laptop:

?View Code VBSCRIPT
Function IsLaptop(strComputer)
    On Error Resume Next
    Set objWMIService = GetObject( "winmgmts://" & strComputer & "/root/cimv2" )
    Set colItems = objWMIService.ExecQuery( "Select * from Win32_Battery", , 48 )
    IsLaptop = False
    For Each objItem in colItems
        IsLaptop = True
    Next
    If Err Then Err.Clear
    On Error GoTo 0
End Function

Example of use

?View Code VBSCRIPT
If IsLaptop( "." ) Then
    WScript.Echo "Laptop
Else
    WScript.Echo "Desktop or server
End If


Shell out a command line with switches:

?View Code VBSCRIPT
Sub RunSwch(ByVal strRunCmd, strRunSwitch)
Dim objWshShell
    Set objWshShell = CreateObject("WScript.Shell")
    objWshShell.Run Chr(34) & strRunCmd & Chr(34)& " " & strRunSwitch, 1, True
    Set objWshShell = Nothing
End Sub

Example of use

?View Code VBSCRIPT
RunSwch "C:\Program Files\ApplicationX\Start.exe","/S /X /Log C:\log.log"


Shell out a command line without switches:

?View Code VBSCRIPT
Sub Run(ByVal strRunCmd)
Dim objWshShell
    Set objWshShell = CreateObject("WScript.Shell")
    objWshShell.Run Chr(34) & strRunCmd & Chr(34), 1, True
    Set objWshShell = Nothing
End Sub

Example of use

?View Code VBSCRIPT
Run "C:\Program Files\ApplicationX\Start.exe"

PowerShell 2.0 Release Candidate for Windows Vista and Server 2008

Still waiting for PowerShell 2.0 for Windows XP and Server 2003, but this is a good start.

Read more from the source: http://blogs.msdn.com/powershell/archive/2009/08/14/powershell-2-0-for-windows-vista-and-windows-server-2008-release-candidate.aspx

Download here: https://connect.microsoft.com/windowsmanagement/Downloads