Visual Studio for Mac8.3.1开发的mac OS小应用
Visual Studio for Mac8.3.1 和 Xcode11.2 的开发环境
系统是macOS 11.7

上面是开发时的Viewcontroller.cs截图,下面详细代码写在Viewcontroller.cs 中
using AppKit;
using Foundation;
namespace CountdownReminder
{
public partial class ViewController : NSViewController
{
private NSTimer _countdownTimer;
private int _remainingSeconds;
public ViewController(IntPtr handle) : base(handle) { }
public override void ViewDidLoad()
{
base.ViewDidLoad();
}
// 开始倒计时按钮的 Action
partial void StartCountdown(NSObject sender)
{
// 设置倒计时总秒数(例如 10 秒)
_remainingSeconds = 10;
UpdateLabel();
// 创建每秒触发一次的 NSTimer
_countdownTimer = NSTimer.CreateRepeatingScheduledTimer(1.0, (timer) =>
{
_remainingSeconds--;
// 在主线程上更新 UI
InvokeOnMainThread(() =>
{
UpdateLabel();
if (_remainingSeconds <= 0)
{
_countdownTimer.Invalidate();
_countdownTimer = null;
ShowAlert();
}
});
});
}
private void UpdateLabel()
{
// 假设你在 Storyboard 中放置了一个名为 countdownLabel 的 Label
countdownLabel.StringValue = $"剩余时间:{_remainingSeconds} 秒";
}
// ... 后续添加 ShowAlert 方法
}
}
private void ShowAlert()
{
var alert = new NSAlert()
{
AlertStyle = NSAlertStyle.Informational,
MessageText = "倒计时结束!",
InformativeText = "您设定的时间已经到了。",
};
alert.AddButton("确定");
alert.AddButton("稍后提醒");
// 以模态窗口方式运行(会阻塞当前窗口)
var response = alert.RunModal();
if (response == (nint)1001) // 点击了"稍后提醒"
{
StartCountdown(new NSObject());
}
}
StartCountDown是button的名字,事件就以它的名字了
CountdownLabel是个Label
界面在xcode中做:
在 Visual Studio for Mac 中,双击 Main.storyboard ,双击无效就右键打开方式,选择 Xcode Interface Builder 中打开界面设计器
你需要:
-
从控件库中拖拽一个 Label 到窗口上,命名为
countdownLabel。 -
拖拽一个 Button,标题设为"开始倒计时"。
-
按住 Ctrl 从 Button 拖拽到 ViewController 代码中,创建一个 Action,命名为
StartCountdown。 -
按住 Ctrl 从 Label 拖拽到代码中,创建一个 Outlet,命名为
countdownLabel。
上述代码是deepseek 给的,亲测可用。无错。是个简单可以快速了解 vs for mac 带有定时线程,message box框的好例子

浙公网安备 33010602011771号