Powershell如何在Powershell GUI exe中嵌入图标

时间:2018-11-19 14:13:30

标签: powershell

我创建了一个powershell gui,我想在Windows.form中插入一个图标。
我这样做是用ps2exe生成了一个exe文件。

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()

#region begin GUI{ 

$Form                            = New-Object system.Windows.Forms.Form
$Form.ClientSize                 = '400,230'
$Form.text                       = "Test"
$Form.TopMost                    = $false
$Icon                            = New-Object system.drawing.icon (".\icon\test.ico")
$Form.Icon                       = $Icon

如果我将exe的dir图标与test.ico一起使用,则一切正常,但是现在我将图标合并到代码中,而无需将exe的图标目录带入。
有可能做到吗?怎么样?

谢谢

1 个答案:

答案 0 :(得分:9)

您可以使用如下所示的base64编码图像将图形信息嵌入代码中:

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()

$Form            = New-Object system.Windows.Forms.Form
$Form.ClientSize = '400,230'
$Form.text       = "Test"
$Form.TopMost    = $false

# This base64 string holds the bytes that make up the orange 'G' icon (just an example for a 32x32 pixel image)
$iconBase64      = 'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTnU1rJkAAAB50lEQVRIS7WWzytEURTHZ2FhaWFhYWFhYWFhaWFh6c+wsGCapJBJU0hRSrOgLBVSmkQoSpqyUJISapIFJU0i1KQp1PG9826vO9+Z97Pr22dz3pxzv/PO/fUSkvxfOLYOx9bh2DocBzPZKlPtku2VuS7JtMlwIydUw7EnGO50Rd4ehPRdlru87GWUMZVU4LgOqLza0cP56PdHNga4NthgsUc+i3qIQOH9qDzAYLZTyiVd7Ah/8/lGztclNyLbY5JfksKxeuiKRvAzwOy93OsyR+9Pam6HajLHm5UfXhTQT34GqDH1eCGjTZxjkmqQmQ5+6Gdgth5NQLsoIRwca7AoTZ1k1UM0p7Y/QXCsof4sdOvRrRlgeZgyu49eY/0cTDO76ShzcJnTQ0O0NvA2XioWqjIrcKy5PdQ1kLl90CKsVC9F2GiYVVPuiQaDiRb1TzGWw9eHzoEiGGwO6hpHWFRe04vuu4pggCPIFPwowSWmAXa/qdKr5zaOaQBwyps6W+UEh/gGtasFlrjCKC2+ATia15WucHpf76vna/2ylVLntnmeRzbApsUQ4RXZwAFnAC7eMMLNSrWhDEC6RfUac1D3+sRew87HhVzvC4PjYLBecRxhDsByn/qEoYRqOLYOx9bh2DocWyaZ+APgBBKhVfsHwAAAAABJRU5ErkJggg=='
$iconBytes       = [Convert]::FromBase64String($iconBase64)
$stream          = New-Object IO.MemoryStream($iconBytes, 0, $iconBytes.Length)
$stream.Write($iconBytes, 0, $iconBytes.Length);
$iconImage       = [System.Drawing.Image]::FromStream($stream, $true)
$Form.Icon       = [System.Drawing.Icon]::FromHandle((New-Object System.Drawing.Bitmap -Argument $stream).GetHIcon())

[void]$Form.ShowDialog()

# when done, dispose of the form
$Form.Dispose()

要将自己的图像转换为base64字符串,有很多在线转换器,例如this one

反之亦然(将base64图像数据转换回图形图像),他们也有一个针对该here的页面

当然,您也可以使用Powershell转换为Base64:

[Convert]::ToBase64String((Get-Content ".\icon\test.ico" -Encoding Byte))