Can`t open a form in another thread.

Ask questions about creating Graphical User Interfaces (GUI) in PowerShell and using WinForms controls.
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
This topic is 4 years and 5 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked
TolikTipaTut1
Posts: 8
Last visit: Fri Jan 27, 2023 6:53 am

Can`t open a form in another thread.

Post by TolikTipaTut1 »

Hello!
I`m creating a Form in another thread using powershell.
I created my own class
  1. class MainForm : System.Windows.Forms.Form {
  2. <#some code#>
  3. }
Form name is "Start_Window". I`m using "ShowDialog()" method to show it.
If i run my script in ISE, "Start_Window" appears.
But if i run my script using Powershell Studio 2019, nothing happens ...
This is my code:
  1.  $Start_Window_syncHash = [hashtable]::Synchronized(@{})
  2.    $Start_Window_Runspace = [runspacefactory]::CreateRunspace()
  3.     $Start_Window_Runspace.ApartmentState = "STA"
  4.     $Start_Window_Runspace.ThreadOptions = "ReuseThread"
  5.     $Start_Window_Runspace.Open()
  6.     $Start_Window_Runspace.SessionStateProxy.SetVariable("Start_Window_syncHash",$Start_Window_syncHash)
  7.     $Start_Window_Cmd = [PowerShell]::Create().AddScript({
  8.     class MainForm : System.Windows.Forms.Form {
  9.     <#some code#>
  10.      }
  11.       <#some code#> ....
  12.       $Start_Window_syncHash.Start_Window = [MainForm]::new()
  13.       $Start_Window_syncHash.Start_Window.ShowDialog() | Out-Null
  14.       $Start_Window_syncHash.Error = $Error
  15.     })
  16.     $Start_Window_Cmd.Runspace = $Start_Window_Runspace
  17.     $Start_Window_data = $Start_Window_Cmd.BeginInvoke()
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Can`t open a form in another thread.

Post by jvierra »

Your code shows a windows for me. Just copy and paste into a console but first add this line:
Add-Type -AssemblyName System.windows.Forms

The following will give you some idea of how this is done and how to get information back after the form has closed. Try not to use the synchash when not needed.

Code: Select all

$scriptCode = {

	class MainForm : System.Windows.Forms.Form {
		MainForm(){
			$this.StartPosition = 'CenterScreen'
			$b = [System.Windows.Forms.Button]@{Name='buttonTest';Text='Test Form'}
			$this.Controls.Add($b)
			$this.Controls['buttonTest'].add_Click({Write-Host 'hello'})
		}
	}
			
	<#some code#>
	$form = [MainForm]::new()
	$syncHash.Form = $form 
	$form.ShowDialog() | Out-Null
}

Add-Type -AssemblyName System.Windows.Forms

$syncHash = [hashtable]::Synchronized(@{})
$runspace = [runspacefactory]::CreateRunspace()
$runspace.ApartmentState = 'STA'
$runspace.ThreadOptions = 'ReuseThread'
$runspace.Open()
$runspace.SessionStateProxy.SetVariable('syncHash',$syncHash)
$ps = [PowerShell]::Create().AddScript($scriptCode)
$ps.Runspace = $runspace
$asyncResult = $ps.Invoke()
$ps.Streams.Information
$ps.Streams.Error
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Can`t open a form in another thread.

Post by jvierra »

This is how to use InvokeAsync to collect data returned.

Code: Select all

$scriptCode = {

	class MainForm : System.Windows.Forms.Form {
		MainForm(){
			$this.StartPosition = 'CenterScreen'
			$this.add_Load({
            })
			$b = [System.Windows.Forms.Button]@{Name='buttonTest';Text='Test Form'}
			$this.Controls.Add($b)
			$this.Controls['buttonTest'].add_Click({Write-Host 'hello'})
		}
		
	}
			
	<#some code#>
	$form = [MainForm]::new()
	$syncHash.Form = $form 
	$form.ShowDialog() | Out-Null
	# this will bcome output
	'This is an output message'
}

Add-Type -AssemblyName System.Windows.Forms

$syncHash = [hashtable]::Synchronized(@{})
$runspace = [runspacefactory]::CreateRunspace()
$runspace.ApartmentState = 'STA'
$runspace.ThreadOptions = 'ReuseThread'
$runspace.Open()
$runspace.SessionStateProxy.SetVariable('syncHash',$syncHash)
$ps = [PowerShell]::Create().AddScript($scriptCode)
$ps.Runspace = $runspace
$asyncResult = $ps.BeginInvoke()
pause  # let this pause until you close the form
$ps.EndInvoke($asyncResult)  # regular output is collected here

# alternate streams are here
$ps.Streams.Information
$ps.Streams.Error
$ps.Streams.Verbose
# ... etc
TolikTipaTut1
Posts: 8
Last visit: Fri Jan 27, 2023 6:53 am

Re: Can`t open a form in another thread.

Post by TolikTipaTut1 »

jvierra, thank you for your answer!

But I still don`t understand...
In your code you used "$ps.Invoke()" method to open the window. This method opens a window. But while the window is open, the code should execute further in another thread... And if I use "Invoke()" method instead "BeginInvoke()", I should close the window to continue executing the code...

My code is below
  1. Add-Type -AssemblyName System.Windows.Form
  2. function Main
  3. {
  4.     try
  5.     {
  6.         [xml]$Script_Conf = Get-Content .\Main_Conf.xml -ErrorAction Stop
  7.         Write-Host "Конфигурационный файл приложения существует! Запускаю выполнение!" -ForegroundColor Green
  8.         $Plane_Pattern_Path = $Script_Conf.config.Plane_Pattern_Path
  9.     }
  10.     Catch [System.Management.Automation.ItemNotFoundException] {
  11.         Write-Host "В папке со скриптом не найден конфигурационный приложения!" -ForegroundColor Red
  12.         Write-Host "Переместите конфигурационный файл в папку, где будет запусакться скрипт!" -ForegroundColor Red
  13.         Write-Host "Прекращаю работу..." -ForegroundColor Red
  14.         return;
  15.     }
  16.    
  17.     $Start_Window_syncHash = [hashtable]::Synchronized(@{ })
  18.     $Start_Window_Runspace = [runspacefactory]::CreateRunspace()
  19.     $Start_Window_Runspace.ApartmentState = "STA"
  20.     $Start_Window_Runspace.ThreadOptions = "ReuseThread"
  21.     $Start_Window_Runspace.Open()
  22.     $Start_Window_Runspace.SessionStateProxy.SetVariable("Start_Window_syncHash", $Start_Window_syncHash)
  23.     $Start_Window_Cmd = [PowerShell]::Create().AddScript({
  24.             Add-Type -AssemblyName System.Windows.Forms
  25.             Add-Type -AssemblyName System.Drawing
  26.             param ([xml]$_config,
  27.                 [string]$_plane_pattern_path)
  28.             Class StartModeling: System.Windows.Forms.Button
  29.             {
  30.                 [System.Windows.Forms.Button]$Butt
  31.                
  32.                 [void] Init ()
  33.                 {
  34.                     $this.Location = [System.Drawing.Point]::new(100, 70)
  35.                     $this.Size = [System.Drawing.Size]::new(200, 60)
  36.                     $this.Font = [System.Drawing.Font]::new('Times New Roman', 14, [System.Drawing.FontStyle]::Bold)
  37.                     $this.Text = 'Начать моделирование'
  38.                 }
  39.                
  40.                 StartModeling ()
  41.                 {
  42.                     $this.Init()
  43.                 }
  44.                
  45.                 [void] Check_Config ()
  46.                 {
  47.                    
  48.                 }
  49.             }
  50.            
  51.             Class ShowMe: System.Windows.Forms.Button
  52.             {
  53.                 [System.Windows.Forms.Button]$Butt
  54.                
  55.                 [void] Init ()
  56.                 {
  57.                     $this.Size = [System.Drawing.Size]::new(200, 60)
  58.                     $this.Location = [System.Drawing.Point]::new(100, 250)
  59.                     $this.Text = 'Автор'
  60.                     $this.Font = [System.Drawing.Font]::new('Times New Roman', 14, [System.Drawing.FontStyle]::Bold)
  61.                     $this.Add_Click({
  62.                             $this.ShowAuthor()
  63.                         })
  64.                 }
  65.                
  66.                 ShowMe ()
  67.                 {
  68.                     $this.Init()
  69.                 }
  70.                
  71.                 [Void] ShowAuthor ()
  72.                 {
  73.                     [System.Windows.Forms.MessageBox]::SHow("Автор: Я.Я. Месенгисер", "Автор")
  74.                 }
  75.             }
  76.            
  77.             Class ShowPatterns: System.Windows.Forms.Button
  78.             {
  79.                 [System.Windows.Forms.Button]$Butt
  80.                
  81.                 [void] Init ()
  82.                 {
  83.                     $this.Size = [System.Drawing.Size]::new(200, 60)
  84.                     $this.Location = [System.Drawing.Point]::new(100, 160)
  85.                     $this.Font = [System.Drawing.Font]::new('Times New Roman', 14, [System.Drawing.FontStyle]::Bold)
  86.                     $this.Text = 'Настроить шаблоны'
  87.                 }
  88.                
  89.                 ShowPatterns ()
  90.                 {
  91.                     $this.Init()
  92.                 }
  93.             }
  94.            
  95.             Class MainForm: System.Windows.Forms.Form
  96.             {
  97.                 [StartModeling]$StartModeling
  98.                 [ShowMe]$ShowAuthor
  99.                 [ShowPatterns]$ShowPatterns
  100.                 [System.Windows.Forms.Form]$PatConf
  101.                
  102.                 [void] Init ()
  103.                 {
  104.                     $this.Size = [System.Drawing.Size]::new(400, 500)
  105.                    
  106.                     $this.StartModeling = [StartModeling]::new()
  107.                     $this.ShowAuthor = [ShowMe]::new()
  108.                     $this.ShowPatterns = [ShowPatterns]::new()
  109.                    
  110.                     $this.ShowPatterns.Add_Click({
  111.                             $this.Parent.PatConf.ShowDialog()
  112.                         })
  113.                    
  114.                     $this.Controls.Add($this.StartModeling)
  115.                     $this.Controls.Add($this.ShowAuthor)
  116.                     $this.Controls.Add($this.ShowPatterns)
  117.                 }
  118.                
  119.                 MainForm ([System.Windows.Forms.Form]$_patConf)
  120.                 {
  121.                     $this.Init()
  122.                     $this.PatConf = $_patConf
  123.                 }
  124.             }
  125.            
  126.             Class CreatePattern: System.Windows.Forms.Button
  127.             {
  128.                 [void] Init ()
  129.                 {
  130.                     $this.Location = [System.Drawing.Point]::new(50, 300)
  131.                     $this.Size = [System.Drawing.Size]::new(250, 30)
  132.                     $this.TextAlign = [System.Drawing.ContentAlignment]::MiddleCenter
  133.                     $this.Text = "Создать шаблон"
  134.                 }
  135.                
  136.                 CreatePattern ()
  137.                 {
  138.                     $this.Init()
  139.                 }
  140.             }
  141.            
  142.             Class UpdatePattern: System.Windows.Forms.Button
  143.             {
  144.                
  145.                 [bool]$IsShown
  146.                
  147.                 [void] Init ()
  148.                 {
  149.                     $this.Location = [System.Drawing.Point]::new(370, 300)
  150.                     $this.Size = [System.Drawing.Size]::new(250, 30)
  151.                     $this.TextAlign = [System.Drawing.ContentAlignment]::MiddleCenter
  152.                     $this.Text = "Просмотр шаблона"
  153.                 }
  154.                
  155.                 UpdatePattern ()
  156.                 {
  157.                     $this.Init()
  158.                 }
  159.                
  160.                 ViewPatternConf ([xml]$PatternConf, [System.Windows.Forms.DataGridView]$GetPatterns, [System.Windows.Forms.DataGridView]$UpdatePatterns)
  161.                 {
  162.                     $this.ClearPatternWindow($UpdatePatterns)
  163.                     $Selected = $GetPatterns.SelectedCells.Count
  164.                     if ($Selected -eq 1)
  165.                     {
  166.                         $this.Parent.UpdatePatterns.Visible = $true
  167.                         $this.Parent.SavePattern.Visible = $true
  168.                         $this.Parent.DeletePattern.Visible = $true
  169.                         $PatternNum = $GetPatterns.CurrentCell.RowIndex
  170.                         $this.UpdateRows([xml]$PatternConf, [System.Windows.Forms.DataGridView]$UpdatePatterns, $PatternNum)
  171.                     }
  172.                     if ($Selected -gt 1)
  173.                     {
  174.                         [System.Windows.Forms.MessageBox]::Show("Вы не можете выбрать более одного шаблона для редактирования!")
  175.                     }
  176.                 }
  177.                
  178.                 ClearPatternWindow ([System.Windows.Forms.DataGridView]$UpdatePatterns)
  179.                 {
  180.                     $Rows = $UpdatePatterns.Rows.Count
  181.                     if ($Rows -gt 0)
  182.                     {
  183.                         for ($i = 0; $i -le $Rows - 1; $i++)
  184.                         {
  185.                             $UpdatePatterns.Rows.RemoveAt(0)
  186.                         }
  187.                     }
  188.                 }
  189.                
  190.                 UpdateRows ([xml]$PatternConf, [System.Windows.Forms.DataGridView]$UpdatePatterns, [int]$PatternNum)
  191.                 {
  192.                     if ($PatternConf.Patterns.ChildNodes.Count -eq 1)
  193.                     {
  194.                         $UpdatePatterns.Rows.Add('Имя шаблона', $PatternConf.Patterns.Pattern.PatternName)
  195.                         $UpdatePatterns.Rows.Add('Модель', $PatternConf.Patterns.Pattern.Model)
  196.                         $UpdatePatterns.Rows.Add('Минимальная скорость полета', $PatternConf.Patterns.Pattern.MinSpeed)
  197.                         $UpdatePatterns.Rows.Add('Максимальная скорость полета', $PatternConf.Patterns.Pattern.MaxSpeed)
  198.                         $UpdatePatterns.Rows.Add('Максимальный прирост скорости (1 сек)', $PatternConf.Patterns.Pattern.SpeedAdjust)
  199.                         $UpdatePatterns.Rows.Add('Максимальный сброс скорости (1 сек)', $PatternConf.Patterns.Pattern.SpeedDecrease)
  200.                         $UpdatePatterns.Rows.Add('Максимальный угол поворота (1 сек)', $PatternConf.Patterns.Pattern.MaxRotAng)
  201.                     }
  202.                     if ($PatternConf.Patterns.ChildNodes.Count -gt 1)
  203.                     {
  204.                         $UpdatePatterns.Rows.Add('Имя шаблона', $PatternConf.Patterns.Pattern[$PatternNum].PatternName)
  205.                         $UpdatePatterns.Rows.Add('Модель', $PatternConf.Patterns.Pattern[$PatternNum].Model)
  206.                         $UpdatePatterns.Rows.Add('Минимальная скорость полета', $PatternConf.Patterns.Pattern[$PatternNum].MinSpeed)
  207.                         $UpdatePatterns.Rows.Add('Максимальная скорость полета', $PatternConf.Patterns.Pattern[$PatternNum].MaxSpeed)
  208.                         $UpdatePatterns.Rows.Add('Максимальный прирост скорости (1 сек)', $PatternConf.Patterns.Pattern[$PatternNum].SpeedAdjust)
  209.                         $UpdatePatterns.Rows.Add('Максимальный сброс скорости (1 сек)', $PatternConf.Patterns.Pattern[$PatternNum].SpeedDecrease)
  210.                         $UpdatePatterns.Rows.Add('Максимальный угол поворота (1 сек)', $PatternConf.Patterns.Pattern[$PatternNum].MaxRotAng)
  211.                     }
  212.                 }
  213.             }
  214.            
  215.             Class SavePattern: System.Windows.Forms.Button
  216.             {
  217.                 [void] Init()
  218.                 {
  219.                     $this.Location = [System.Drawing.Point]::new(50, 620)
  220.                     $this.Size = [System.Drawing.Size]::new(250, 30)
  221.                     $this.TextAlign = [System.Drawing.ContentAlignment]::MiddleCenter
  222.                     $this.Text = "Сохранить шаблон"
  223.                     $this.Visible = $false
  224.                 }
  225.                
  226.                 SavePattern ()
  227.                 {
  228.                     $this.Init()
  229.                 }
  230.                
  231.                 Request_Answer()
  232.                 {
  233.                     [System.Windows.Forms.DialogResult]$User_Answer = [System.Windows.Forms.MessageBox]::Show("Вы уверены ?", "Запрос подтверждения", [System.Windows.Forms.MessageBoxButtons]::YesNoCancel)
  234.                 }
  235.                
  236.             }
  237.            
  238.             Class DeletePattern: System.Windows.Forms.Button
  239.             {
  240.                 [void] Init ()
  241.                 {
  242.                     $this.Location = [System.Drawing.Point]::new(370, 620)
  243.                     $this.Size = [System.Drawing.Size]::new(250, 30)
  244.                     $this.TextAlign = [System.Drawing.ContentAlignment]::MiddleCenter
  245.                     $this.Text = "Удалить шаблон"
  246.                     $this.Visible = $false
  247.                 }
  248.                
  249.                 DeletePattern ()
  250.                 {
  251.                     $this.Init()
  252.                 }
  253.             }
  254.            
  255.             Class GetPatterns: System.Windows.Forms.DataGridView
  256.             {
  257.                 [void] Init()
  258.                 {
  259.                     $this.Location = [System.Drawing.Point]::new(50, 50)
  260.                     $this.Size = [System.Drawing.Size]::new(570, 230)
  261.                     $this.AllowUserToAddRows = $false
  262.                     $this.AllowUserToDeleteRows = $false
  263.                 }
  264.                
  265.                 GetPatterns ()
  266.                 {
  267.                     $this.Init()
  268.                 }
  269.             }
  270.            
  271.             Class UpdatePatterns: System.Windows.Forms.DataGridView
  272.             {
  273.                 [void] Init()
  274.                 {
  275.                     $this.Location = [System.Drawing.Point]::new(50, 360)
  276.                     $this.Size = [System.Drawing.Size]::new(570, 230)
  277.                     $this.AllowUserToAddRows = $false
  278.                     $this.AllowUserToDeleteRows = $false
  279.                     $this.Visible = $false
  280.                 }
  281.                
  282.                 UpdatePatterns ()
  283.                 {
  284.                     $this.Init()
  285.                 }
  286.             }
  287.            
  288.             Class PatternProperties: System.Windows.Forms.DataGridViewColumn
  289.             {
  290.                 [void] Init ()
  291.                 {
  292.                     $this.Frozen = $true
  293.                     $this.DefaultCellStyle.Alignment = [System.Windows.Forms.DataGridViewContentAlignment]::MiddleCenter
  294.                     $this.CellTemplate = [System.Windows.Forms.DataGridViewTextBoxCell]::new()
  295.                     $this.HeaderCell.Style.Alignment = [System.Windows.Forms.DataGridViewContentAlignment]::MiddleCenter
  296.                 }
  297.                
  298.                 PatternProperties ()
  299.                 {
  300.                     $this.Init()
  301.                 }
  302.             }
  303.            
  304.             Class Main_Window: System.Windows.Forms.Form
  305.             {
  306.                 [CreatePattern]$CreatPattern
  307.                 [UpdatePattern]$UpdatePattern
  308.                 [SavePattern]$SavePattern
  309.                 [DeletePattern]$DeletePattern
  310.                 [GetPatterns]$GetPatterns
  311.                 [UpdatePatterns]$UpdatePatterns
  312.                 [PatternProperties]$PatternProperty
  313.                 [PatternProperties]$PatternName
  314.                 [PatternProperties]$PatternHost
  315.                 [xml]$PatternConf
  316.                
  317.                 [void] Init ()
  318.                 {
  319.                     $a = $this.PatternConf.Patterns.Pattern.Count
  320.                     $this.Size = [System.Drawing.Size]::new(700, 800)
  321.                     $this.BackColor = [System.Drawing.Color]::AliceBlue
  322.                     $this.Add_load({
  323.                             try
  324.                             {
  325.                                 $_path = $_plane_pattern_path
  326.                                 $this.PatternConf = Get-Content $_path -ErrorAction Stop
  327.                             }
  328.                             catch [System.Management.Automation.ItemNotFoundException] {
  329.                                 [System.Windows.Forms.MessageBox]::Show("Файл шаблонов отсутствует! Переместите файл с шаблонами в папку, где находится скрипт, и перезапустите скрипт, или создайте шаблоны в интерфейсе!", "Внимание!")
  330.                             }
  331.                             if ($this.PatternConf.Patterns.ChildNodes.Count -eq 1)
  332.                             {
  333.                                 $this.GetPatterns.Rows.Add($this.PatternConf.Patterns.Pattern.PatternName)
  334.                             }
  335.                             if ($this.PatternConf.Patterns.ChildNodes.Count -gt 1)
  336.                             {
  337.                                 for ($i = 0; $i -lt $this.PatternConf.Patterns.Pattern.Count; $i++)
  338.                                 {
  339.                                     $this.GetPatterns.Rows.Add($this.PatternConf.Patterns.Pattern[$i].PatternName)
  340.                                 }
  341.                             }
  342.                         })
  343.                    
  344.                     $this.CreatPattern = [CreatePattern]::new()
  345.                     $this.Controls.Add($this.CreatPattern)
  346.                    
  347.                     $this.UpdatePattern = [UpdatePattern]::new()
  348.                     $this.Controls.Add($this.UpdatePattern)
  349.                     $this.UpdatePattern.Add_Click({
  350.                             $this.ViewPatternConf($this.Parent.PatternConf, $this.Parent.GetPatterns, $this.Parent.UpdatePatterns)
  351.                         })
  352.                    
  353.                     $this.SavePattern = [SavePattern]::new()
  354.                     $this.Controls.Add($this.SavePattern)
  355.                     $this.SavePattern.Add_Click({
  356.                             $this.Request_Answer()
  357.                             $this.Parent.UpdatePatterns.Visible = $false
  358.                             $this.Visible = $false
  359.                             $this.Parent.DeletePattern.Visible = $false
  360.                         })
  361.                    
  362.                     $this.DeletePattern = [DeletePattern]::new()
  363.                     $this.Controls.Add($this.DeletePattern)
  364.                    
  365.                     $this.GetPatterns = [GetPatterns]::new()
  366.                     $this.Controls.Add($this.GetPatterns)
  367.                    
  368.                     $this.UpdatePatterns = [UpdatePatterns]::new()
  369.                     $this.Controls.Add($this.UpdatePatterns)
  370.                    
  371.                     $this.PatternProperty = [PatternProperties]::new()
  372.                     $this.PatternProperty.Width = 528
  373.                     $this.PatternProperty.HeaderText = 'Название шаблона'
  374.                     $this.PatternProperty.DataPropertyName = 'Pattern Property'
  375.                     $this.PatternProperty.ReadOnly = $true
  376.                     $this.PatternProperty.Name = 'PatternProperty'
  377.                     $this.GetPatterns.Columns.Add($this.PatternProperty)
  378.                    
  379.                     $this.PatternName = [PatternProperties]::new()
  380.                     $this.PatternName.Width = 352
  381.                     $this.PatternName.HeaderText = 'Параметр'
  382.                     $this.PatternName.DataPropertyName = 'Pattern Name'
  383.                     $this.PatternName.ReadOnly = $true
  384.                     $this.PatternName.Name = 'Param'
  385.                     $this.UpdatePatterns.Columns.Add($this.PatternName)
  386.                    
  387.                     $this.PatternHost = [PatternProperties]::new()
  388.                     $this.PatternHost.Width = 176
  389.                     $this.PatternHost.HeaderText = 'Значение'
  390.                     $this.PatternHost.DataPropertyName = 'Pattern Host'
  391.                     $this.PatternHost.ReadOnly = $false
  392.                     $this.PatternHost.Name = 'Host'
  393.                     $this.UpdatePatterns.Columns.Add($this.PatternHost)
  394.                    
  395.                 }
  396.                
  397.                 Main_Window ()
  398.                 {
  399.                     $this.Init()
  400.                 }
  401.             } #::Main_Window
  402.            
  403.             $Start_Window_syncHash.PatternConfigWindow = [Main_Window]::new()
  404.             $Start_Window_syncHash.Start_Window = [MainForm]::new($Start_Window_syncHash.PatternConfigWindow)
  405.             $Start_Window_syncHash.Start_Window.ShowDialog() | Out-Null
  406.             $Start_Window_syncHash.Error = $Error
  407.         })
  408.     $Start_Window_Cmd.AddArgument($Script_Conf) | Out-Null
  409.     $Start_Window_Cmd.AddArgument($Plane_Pattern_Path) | Out-Null
  410.     $Start_Window_Cmd.Runspace = $Start_Window_Runspace
  411.     $Start_Window_data = $Start_Window_Cmd.BeginInvoke()
  412.     Start-Sleep 4
  413.     $Start_Window_data
  414. }
  415. Main
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Can`t open a form in another thread.

Post by jvierra »

I posted two examples that you can run at a prompt. The second one uses BeginInvoke. Run them at a prompt and try to understand what I am showing you. Posting a very long sript does not help to solve the issue. Understanding how to use runspaces is the first thing to do.

When posting long scripts please attach them as a file usable in PowerShell Studio (PSF) to illustrate your issue.

Run and try to understand m code and you will begin to see how this needs to work.
TolikTipaTut1
Posts: 8
Last visit: Fri Jan 27, 2023 6:53 am

Re: Can`t open a form in another thread.

Post by TolikTipaTut1 »

Thank you very much!

Actually, I`ve got some kind of "homework".
The task is:
I need to get the shortest car route. So, I need 3 threads:
GUI for users to interact with, the engine and some kind of "bridge" thread. Sorry for my english.

How can I create events in powershell ?
For example:
A user presses a button on form (calculate route)
Then I need to sart the calculation process. I know that i can use "button.Add_Click({<# code here #>})", but I need to create threads instead...
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Can`t open a form in another thread.

Post by jvierra »

I cannot even begin to guess what you are trying to do.

PowerShell is not multithreaded, You can use jobs to do calculations in the background.
If you are not an experienced programmer or an experienced PowerShell coder then I suggest not doing this in a form.

Why is this "homework"? What are you studying that requires using PowerShell?
TolikTipaTut1
Posts: 8
Last visit: Fri Jan 27, 2023 6:53 am

Re: Can`t open a form in another thread.

Post by TolikTipaTut1 »

I am a university of geodesy and cartography student.
Our lecturer gave us this homework.
I insisted on using С# perform this task ...
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Can`t open a form in another thread.

Post by jvierra »

Did your professor require threads? PowerShell does not do threads. Runspaces are much more complex and do not do forms well unless you are a vvery experienced programmer with Windows forms.

I cannot believe a professor of "mapping" would require PowerShell. It is not an application development language. It is an automation language for admins and developers to use to built tools for diagnostics and reporting. Applications requires a different system. C# is an applications development language and more.

Also you do not need to use threads to do any simple calculations. You can just executer good mathematical formulas that are design to solve issues like the "salesmeans' route problem".

Just add the code to an event on a button and click the button.

On modern processors the shortest route algorithms for routes with fewer that 50 segments can execute in a second or two. I see no need for threads.
TolikTipaTut1
Posts: 8
Last visit: Fri Jan 27, 2023 6:53 am

Re: Can`t open a form in another thread.

Post by TolikTipaTut1 »

Yes, our professor didn't tell me that threads are required.
So, I'll paste code into button.add_click)

P.S. But I'll continue to understand runspaces, because it's really interesting)
Thank you very much for your help!
This topic is 4 years and 5 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked