每日对着电脑屏幕,今天想用c#实现隔一段时间自动让系统提示我休息的功能,代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace eye_rest
{
public partial class Form1 : Form
{
private static readonly IntPtr HWND_BROADCAST = new IntPtr(0xffff);
private const int WM_SYSCOMMAND = 0x0112;
private const int SC_SCREENSAVE = 0xf140;
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
public Form1()
{
InitializeComponent();
bool isStarted = false;
bool isWindowVisible = true;
NotifyIcon notifyIcon = new NotifyIcon();
//notifyIcon.Icon = new Icon("icon.ico");
notifyIcon.Icon = SystemIcons.Information; // 使用系统默认信息图标
notifyIcon.Text = "eye_rest";
notifyIcon.ContextMenuStrip = new ContextMenuStrip();
notifyIcon.ContextMenuStrip.Items.Add("退出", null, (s, e) => Application.Exit()); // 添加“退出”菜单项
while (true)
{
if (!isStarted)
{
Console.WriteLine("程序已经启动,按任意键开始执行...");
//Console.ReadKey();
MessageBox.Show("start");
isStarted = true;
notifyIcon.ShowBalloonTip(1000, "提示", "程序已经开始运行!", ToolTipIcon.Info);
}
Console.WriteLine("休息一下眼睛...");
// 打开屏保
SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_SCREENSAVE, 0);
if (isWindowVisible)
{
// 将窗口隐藏,显示 NotifyIcon
IntPtr hWnd = GetForegroundWindow();
ShowWindow(hWnd, SW_HIDE);
notifyIcon.Visible = true;
isWindowVisible = false;
}
System.Threading.Thread.Sleep(TimeSpan.FromMinutes(1)); //修改想中间间隔的时间,分钟为单位,20分钟就输入20,测试方便1分钟
}
}
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private const int SW_HIDE = 0;
}
}
如果你是使用 Visual Studio 创建的项目,可以在“新建项目”对话框中选择“Windows Forms App (.NET Framework)”或“Windows Forms App (.NET)”模板来创建一个 Windows 应用程序项目。
然后将以下代码拷贝进去,运行后,会弹出一个提示框,回车后,就开始自动计时,间隔一段时间后就会自动弹出屏保,提示眼睛休息一下。