【C#】跨平台创建你的WinForms窗体应用(WindowsUbuntu)
😏★,°:.☆( ̄▽ ̄)/$:.°★ 😏
这篇文章主要介绍多平台创建你的WinForms窗体应用(Windows&Ubuntu)。
学其所用,用其所学。——梁启超
欢迎来到我的博客,一起学习,共同进步。
喜欢的朋友可以关注一下,下次更新不迷路🥞
文章目录
- :smirk:1. WinForm介绍
- :blush:2. 环境安装与配置
- :satisfied:3. WinForms应用示例
- :satisfied:4. VB应用示例
😏1. WinForm介绍
C# WinForms(Windows Forms
)是微软提供的一种用于创建桌面应用程序的图形用户界面(GUI)框架。它基于 .NET Framework 或 .NET Core/.NET 5+,允许开发者通过拖拽控件和编写事件驱动代码快速构建 Windows 应用程序。
核心特点
-
基于控件的开发
WinForms 提供丰富的内置控件(如按钮、文本框、列表框等),支持通过 Visual Studio 设计器直接拖拽布局,简化界面开发流程。 -
事件驱动模型
用户交互(如点击、输入)触发事件,开发者只需编写事件处理逻辑(如按钮的 Click 事件),无需关注底层消息循环。 -
数据绑定支持
支持将控件属性(如 TextBox.Text)与数据源(如数据库、对象)绑定,实现数据自动同步更新。 -
GDI+ 图形绘制
通过 System.Drawing 命名空间提供绘图功能,支持自定义绘制图形、文字和图像。
WinForms用微软自家的API和C#,在Windows平台的支持会好点,因此Win上的许多桌面软件都是基于Visual Studio来开发的,但它也可以跨平台(配合mono可在Linux上编译和运行)。
😊2. 环境安装与配置
Windows上用VS安装使用即可,这里不再赘述。
Ubuntu上需先安装dotnet(C#语言支持):
sudo apt update
sudo apt install -y dotnet-sdk-8.0
# 验证安装
dotnet --version
然后安装mono,Mono 是较早的跨平台 .NET 实现,对 WinForms 支持较好。
sudo apt update
sudo apt install -y mono-complete
mono --version
# 编译
mcs Program.cs -r:System.Windows.Forms.dll -r:System.Drawing.dll
# 运行
mono Program.exe
在Ubuntu上创建窗体应用(两种方式):
1.直接使用dotnet,添加WinForms支持
2.基于mono来编译运行
😆3. WinForms应用示例
创建WinForms应用
dotnet new console -o WinFormsApp
cd WinFormsApp
# 添加 Windows Forms 支持
dotnet add package Microsoft.Windows.Compatibility
创建 Program.cs
using System;
using System.Windows.Forms;class Program
{static void Main(){Application.EnableVisualStyles();Application.Run(new MyForm());}
}class MyForm : Form
{public MyForm(){this.Text = "C# WinForms on Ubuntu";this.Width = 400;this.Height = 300;var label = new Label{Text = "Hello, C# WinForms!",Location = new System.Drawing.Point(100, 100),AutoSize = true};this.Controls.Add(label);var button = new Button{Text = "Click Me",Location = new System.Drawing.Point(100, 150)};button.Click += (sender, e) => MessageBox.Show("Button clicked!");this.Controls.Add(button);}
}
运行:dotnet run
😆4. VB应用示例
此外,mono也可以用来创建VB窗体应用。
安装:
sudo apt install mono-complete mono-vbnc
vbnc --version
创建 WinFormsVB.vb:
Imports System.Windows.FormsPublic Class MainFormInherits FormPublic Sub New()Me.Text = "VB WinForms on Ubuntu"Me.Width = 400Me.Height = 300Dim label As New Labellabel.Text = "Hello, VB WinForms!"label.Location = New Drawing.Point(100, 100)label.AutoSize = TrueMe.Controls.Add(label)Dim button As New Buttonbutton.Text = "Click Me"button.Location = New Drawing.Point(100, 150)AddHandler button.Click, AddressOf ButtonClickMe.Controls.Add(button)End SubPrivate Sub ButtonClick(sender As Object, e As EventArgs)MessageBox.Show("Button clicked!")End Sub
End ClassModule ProgramSub Main()Application.EnableVisualStyles()Application.Run(New MainForm())End Sub
End Module
编译运行:
vbnc WinFormsVB.vb -r:System.Windows.Forms.dll -r:System.Drawing.dll
mono WinFormsVB.exe
以上。