我写了一段非常简单的代码供 Ironruby 检查,如果一切按应有的方式工作:
require "System.Windows.Forms"
include System::Windows::Forms
form = Form.new
form.Show
当我直接在交互式 Ironruby 控制台中键入此代码时,它正常工作,但是当我将此代码保存在 test.rb 文件中并通过命令提示符执行ir test.rb
时,Windows 窗体会弹出并在执行整个代码后立即关闭。有没有办法避免这种行为?我尝试使用 gets,但随后控制台正在等待输入,而表单被冻结。
是的。简单的答案就是将form.Show
更改为Application.Run form
代码完成后窗口立即关闭的原因需要了解模式窗口与无模式窗口。下面是进一步阅读的链接:显示模式和无模式 Windows 窗体
此外,下面是混合模态和无模式的示例:
require 'System.Drawing'
include System::Drawing
require 'System.Windows.Forms'
include System::Windows::Forms
class Dlg <Form
def initialize
self.Text = 'Modal'
self.Load do
self.FormBorderStyle = FormBorderStyle.FixedDialog
showHide = Button.new
showHide.Text = 'Show'
self.Controls.Add(showHide)
showHide.Click do
if @modeless.nil?
@modeless = Form.new
@modeless.StartPosition = FormStartPosition.CenterScreen
@modeless.Text = 'Modeless'
@modeless.FormClosing { @modeless = nil; showHide.Text = 'Show' }
end
if @modeless.Visible
@modeless.Hide # hide a modeless form
showHide.Text = 'Show'
else
@modeless.Show # show a modeless form
showHide.Text = 'Hide'
end
end
ok = Button.new
ok.DialogResult = DialogResult.OK
ok.Text = 'OK'
ok.Location = Point.new(0, showHide.Bottom+10)
self.Controls.Add(ok)
cancel = Button.new
cancel.DialogResult = DialogResult.Cancel
cancel.Text = 'Cancel'
cancel.Location = Point.new(ok.Right+10, ok.Top)
self.Controls.Add(cancel)
end
end
end
dlg = Dlg.new
dlgResult = dlg.ShowDialog # show a modal dialog
if dlgResult != DialogResult.OK
MessageBox.Show('NOT OK') # MessageBox.Show is modal
else
MessageBox.Show('OK')
end