You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在SharpDevelop中使用IronRuby实现点击按钮切换窗体的问题求助

解决IronRuby在SharpDevelop中切换窗体时自动关闭的问题

问题根源

  1. 语法错误:你的changeForm方法使用了C#风格的对象创建语法,IronRuby不支持Form1 form1 = new Form1()这种写法,需遵循Ruby语法规范。
  2. 主窗体关闭导致应用退出:如果MainForm是应用的启动窗体,直接调用Close()会终止整个.NET应用的消息循环,刚打开的Form1会随之被关闭。

解决步骤

1. 编写Form1.rb的必要代码

必须在Form1.rb中定义继承自Form的Form1类,否则无法实例化窗体:

require 'System.Windows.Forms'
include System::Windows::Forms

class Form1 < Form
  def initialize
    super()
    # 可自定义Form1的属性,比如设置窗体标题
    self.Text = "Form1"
  end
end

2. 修正MainForm.rb的代码逻辑

调整changeForm方法的语法,并修改窗体切换逻辑,避免主窗体关闭直接终止应用:

require 'System.Windows.Forms'
require 'Form1.rb'
include System::Windows::Forms

class MainForm < Form
  def initialize
    super()
    self.Text = "MainForm"
    
    # 创建切换按钮并绑定点击事件
    switch_btn = Button.new
    switch_btn.Text = "打开Form1"
    switch_btn.Location = Point.new(20, 20)
    switch_btn.add_Click(method(:changeForm))
    self.Controls.Add(switch_btn)
  end

  def changeForm(sender, e)
    # IronRuby正确的对象实例化语法
    form1 = Form1.new
    # 先隐藏主窗体,而非直接关闭
    self.Hide()
    form1.Show()
    
    # 绑定Form1的关闭事件:当Form1关闭时再关闭主窗体,保证应用正常退出
    form1.FormClosed do |s, args|
      self.Close()
    end
  end
end

# 启动应用程序
Application.Run(MainForm.new)

关键说明

  • 用self.Hide()替代直接Close(),避免主窗体关闭导致应用立即退出。
  • 通过FormClosed事件监听Form1的关闭状态,在Form1关闭后再关闭MainForm,确保应用消息循环持续到用户主动关闭Form1。
  • IronRuby中实例化对象使用类名.new,无需声明变量类型,这是和C#语法的核心区别。

内容的提问来源于stack exchange,提问作者Mila1803

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 02:12:22