Home > Software engineering >  How to disable close button in PowerShell Windows Forms using Add-Type C# code?
How to disable close button in PowerShell Windows Forms using Add-Type C# code?

Time:11-05

I have a Windows Forms in PowerShell where I am trying to disable the close button X. I found a couple of C# code for doing that (Source 1, Source 2), but I can't get it to work with PowerShell 5.1.

Here is my code:

$codeDisableX = @"
private const int CP_NOCLOSE_BUTTON = 0x200;
protected override CreateParams CreateParams
{
    get
    {
        CreateParams myCp = base.CreateParams;
        myCp.ClassStyle = myCp.ClassStyle | CP_NOCLOSE_BUTTON;
        return myCp;
    }
}
"@

Add-Type -TypeDefinition $codeDisableX -ReferencedAssemblies System.Windows.Forms -Language CSharp
Add-Type -AssemblyName System.Windows.Forms

$root = [System.Windows.Forms.Form]::new()
# Remaining code for Windows Forms not included

Would anyone know how I can implement the C# code with PowerShell to disable the close button?

Also, I do not want to use $root.ControlBox = $false.

CodePudding user response:

You need to subclass and extend the existing Form class for the override to have any effect:

Add-Type -AssemblyName System.Windows.Forms
Add-Type @'
using System.Windows.Forms;
public class FormWithoutX : Form {
  protected override CreateParams CreateParams
  {
    get {
      CreateParams cp = base.CreateParams;
      cp.ClassStyle = cp.ClassStyle | 0x200;
      return cp;
    }
  }

}
'@ -ReferencedAssemblies System.Windows.Forms

Now you can create FormWithoutX instead of a Form and the resulting form's close button will be disabled:

$root = [FormWithoutX]::new()
# ...

CodePudding user response:

I'm posting a slight tweak to @Mathias R. Jessen's answer above, in case it helps someone else. I've wrapped the C# code in a custom namespace, and create a new form using [MyForm.FormWithoutX]::new(). This allows keeping the C# code in a variable to use when creating the form:

$codeDisableX = @"
using System.Windows.Forms;

namespace MyForm {
    public class FormWithoutX : Form {
        protected override CreateParams CreateParams {
            get {
                CreateParams cp = base.CreateParams;
                cp.ClassStyle = cp.ClassStyle | 0x200;
                return cp;
            }
        }
    }
}
"@

Add-Type -AssemblyName System.Windows.Forms
Add-Type -TypeDefinition $codeDisableButtonX -ReferencedAssemblies System.Windows.Forms

$root = [MyForm.FormWithoutX]::new()
# Remaining code for Windows Forms not included
  • Related