整理自經典技術分享,彙總 25 個 C# Windows Forms 開發中高頻、實用的技巧,涵蓋視窗外觀、控制項技巧、系統資訊、檔案路徑、資料綁定、報表、郵件啟動等實務場景,附完整程式碼可直接複製套用。
form.Text = string.Empty;
form.ControlBox = false; // 隱藏最小化/最大化/關閉鈕
// 仍保有調整邊框
static void Main()
{
Application.EnableVisualStyles(); // 必須在 Run 前呼叫
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
// 控制項 FlatStyle = FlatStyle.System 才會套用系統主題
form.AcceptButton = btnOK; // Enter 鍵觸發
form.CancelButton = btnCancel; // Esc 鍵觸發
form.ShowInTaskbar = false;
comboFont.Items.AddRange(FontFamily.Families.Cast().Select(f => f.Name).ToArray());
// 或直接加入 FontFamily 物件,配合 DrawMode 自繪預覽
textBox.ContextMenu = new ContextMenu(); // 空選單
// 或 textBox.ContextMenuStrip = new ContextMenuStrip();
dtp.CustomFormat = " "; // 一個空格
dtp.Format = DateTimePickerFormat.Custom;
// 使用者選擇日期後,在 ValueChanged 事件改回 Format = Short
panel.BackColor = Color.FromArgb(128, 200, 220, 240); // Alpha=128 (50%)
// 注意:需在設計器程式碼手動指定 Argb,不要用 ColorDialog 選取
string myDocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string exePath = Application.ExecutablePath; // 含檔名
string exeDir = Path.GetDirectoryName(exePath); // 僅目錄
OperatingSystem os = Environment.OSVersion;
Console.WriteLine($"Version: {os.Version}, Platform: {os.Platform}");
// 現代建議用 RuntimeInformation 或 WMI 取得更詳盡資訊
bool hasMouse = SystemInformation.MousePresent;
int buttons = SystemInformation.MouseButtons;
bool hasWheel = SystemInformation.MouseWheelPresent;
bool swapped = SystemInformation.MouseButtonsSwapped;
string full = @"C:\Data\Report.v2.pdf";
string fileName = Path.GetFileName(full); // "Report.v2.pdf"
string ext = Path.GetExtension(full); // ".pdf"
string nameOnly = Path.GetFileNameWithoutExtension(full); // "Report.v2"
test.udl (文字檔改副檔名)。test.udl,即可看到標準連線字串。
// 方法 1: Lines 屬性 (陣列)
textBox.Lines = new[] { "Line 1", "Line 2", "Line 3" };
// 方法 2: 換行字元
textBox.Text = "Line 1\r\nLine 2\r\nLine 3";
// 方法 3: Environment.NewLine (跨平台安全)
textBox.Text = "Line 1" + Environment.NewLine + "Line 2";
var boolCol = new DataGridBoolColumn { MappingName = "IsActive", AllowNull = false };
// AllowNull=false 強制非 Null,避免顯示灰色方塊
comboBox.DataSource = dt;
comboBox.ValueMember = "Id";
comboBox.DisplayMember = "Name";
listBox.BindingContext = new BindingContext(); // 關鍵:建立獨立 BindingContext
listBox.DataSource = dt;
listBox.ValueMember = "Id";
listBox.DisplayMember = "Name";
foreach (Control ctrl in crystalReportViewer1.Controls)
{
if (ctrl is StatusBar sb) sb.Visible = false;
}
var report = new ReportDocument();
report.Load("Report.rpt");
// 設定參數、資料源...
var opts = new ExportOptions
{
ExportFormatType = ExportFormatType.PortableDocFormat,
FormatOptions = new PdfRtfWordFormatOptions(),
ExportDestinationType = ExportDestinationType.DiskFile,
DestinationOptions = new DiskFileDestinationOptions { DiskFileName = @"C:\Out.pdf" }
};
report.Export();
// WinForms
var psi = new ProcessStartInfo
{
FileName = "mailto:to@example.com?cc=cc@example.com&subject=Hello&body=Body%20text",
UseShellExecute = true
};
Process.Start(psi);
// ASP.NET (超連結)
// 寄信
btnSave.PerformClick(); // 引發 Click 事件,比直接呼叫 handler 更完整
[STAThread] // Single-Threaded Apartment
static void Main() { ... }
// 必須:Windows Forms、Clipboard、DragDrop、COM Interop、ActiveX 控制項
// 若無此屬性,剪貼簿、拖放、OpenFileDialog 可能異常或卡死
if (this.InvokeRequired)
this.Invoke(new Action(() => { /* UI 更新 */ }));
else
/* UI 更新 */;
Point screenPos = control.PointToScreen(Point.Empty);
private static MyForm _instance;
public static MyForm Instance => _instance ?? (_instance = new MyForm());
private MyForm() { InitializeComponent(); }
protected override void OnFormClosed(FormClosedEventArgs e)
{
base.OnFormClosed(e);
_instance = null; // 允許重新開啟
}
這 25 個技巧涵蓋了 WinForms 開發 80% 的常見需求。建議將常用片段封裝為**專案共用函式庫** (如 WinFormsHelpers),配合 Snippet 或 ReSharper Live Template,讓團隊一鍵套用,專注核心業務邏輯開發。