🦧

[GTK/C#] C#でGUI作成時のLinuxとWindowsのコーディング

2020/12/29に公開

0. 概要

C#でGUI作成時のLinux(GTKSharp)とWindowsのコーディングの違いを調べました。

1. コード対比

■ Linux

hello_linux.cs
using Cairo;
using Gdk;
using Gtk;
using System;

class MainWindow : Gtk.Window
{
  private bool _toggleDraw = true;

  public MainWindow() : base("Hello World!")
  {
    this.Resize(500, 500);
    this.WindowPosition = WindowPosition.Center;
    this.AddEvents((int)EventMask.ButtonPressMask);
  }
  
  protected override bool OnButtonPressEvent (EventButton evnt)
  {
    _toggleDraw = !_toggleDraw;
    this.QueueDraw();
    return true;
  }
  
  protected override bool OnExposeEvent (EventExpose evnt)
  {
    if (_toggleDraw) {
      using (Context c = CairoHelper.Create(this.GdkWindow)) {
        c.SetSourceRGB(1.000, 0.388, 0.278);
        c.MoveTo(200, 250);
        c.SetFontSize(20);
        c.ShowText("Hello world!");
        c.Fill();
      }
    }
    return true;
  }
  
  protected override bool OnDeleteEvent(Event evnt)
  {
     Application.Quit();
     return true;
  }
}

class HelloWorld
{
  static void Main()
  {
    Application.Init();
    MainWindow window = new MainWindow();
    window.ShowAll();
    Application.Run();
  }
}
mcs hello_linux.cs -pkg:gtk-sharp-2.0 -r:Mono.Cairo

■ Windows

hello_win.cs
using System;
using System.Drawing;
using System.Windows.Forms;

class MainForm : Form
{
  private bool _toggleDraw = true;
  
  public MainForm()
  {
    this.Text = "Hello World!";
    this.ClientSize = new Size(500, 500);
    this.StartPosition = FormStartPosition.CenterScreen;
  }
  
  protected override void OnMouseDown(MouseEventArgs args)
  {
    _toggleDraw = !_toggleDraw;
    this.Invalidate();
  }
  
  protected override void OnPaint(PaintEventArgs args)
  {
    if (_toggleDraw) {
      Graphics g = args.Graphics;
      using (var font = new Font("MS UI Gothic", 20)) {
        g.DrawString("Hello world!", font, Brushes.Tomato, 200, 250);
      }
    }
  }
}

class HelloWorld
{
  [STAThread]
  static void Main()
  {
    Form form = new MainForm();
    Application.Run(form);
  }
}
mcs hello_win.cs -pkg:dotnet -target:winexe

Discussion