首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 基礎建構塊 (三):等待游標、列舉處理程序、開啟瀏覽器、播放 WAV、發送郵件

     編輯:關於C語言

切換游標為等待狀態

// 進入等待
this.Cursor = Cursors.WaitCursor; // 或 Control.Cursor

// 執行耗時操作...

// 恢復預設
this.Cursor = Cursors.Default; // 或 Cursors.Arrow

建議用 try/finally 確保恢復:

Cursor original = this.Cursor;
this.Cursor = Cursors.WaitCursor;
try { /* 長時間工作 */ }
finally { this.Cursor = original; }

列舉系統處理程序

using System.Diagnostics;

Process[] processes = Process.GetProcesses(); // 本機
// Process[] processes = Process.GetProcesses("RemoteMachine"); // 遠端需權限

foreach (Process p in processes)
{
    Console.WriteLine($"PID: {p.Id,6}  Name: {p.ProcessName}");
}

亦可用 Process.GetProcessesByName("notepad") 依名稱過濾。

啟動瀏覽器開啟網址

Process.Start("https://www.example.com"); // 使用系統預設瀏覽器

// 指定瀏覽器
Process.Start(new ProcessStartInfo
{
    FileName = "chrome.exe",
    Arguments = "https://www.example.com",
    UseShellExecute = true // .NET Core 必須 true
});

播放 WAV 檔案

[DllImport("winmm.dll", CharSet = CharSet.Auto)]
private static extern bool PlaySound(string pszSound, IntPtr hmod, uint fdwSound);

// 播放檔案 (同步)
PlaySound(@"C:\Windows\Media\chord.wav", IntPtr.Zero, 0x00020000 /* SND_FILENAME */);

// 非同步播放
PlaySound(@"C:\Sound\alert.wav", IntPtr.Zero, 0x00020001 /* SND_FILENAME | SND_ASYNC */);

現代專案建議使用 System.Media.SoundPlayer (僅支援 .wav) 或 NAudio 庫支援更多格式。

發送電子郵件

using System.Net.Mail;
using System.Net;

var msg = new MailMessage
{
    From = new MailAddress("sender@example.com"),
    Subject = "測試主旨",
    Body = "郵件內容",
    IsBodyHtml = false
};
msg.To.Add("recipient@example.com");

using (var smtp = new SmtpClient("smtp.example.com", 587))
{
    smtp.Credentials = new NetworkCredential("user", "password");
    smtp.EnableSsl = true;
    smtp.Send(msg); // 或 SendMailAsync
}

注意:舊文件提到的 System.Web.Mail.SmtpMail 已過時,請改用 System.Net.Mail。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved