winform壁纸工具:为图片添加当月的日历并设为壁纸
这几天用winform做了一个设置壁纸的小工具, 为图片添加当月的日历并设为壁纸,可以手动设置壁纸,也可以定时设置壁纸,最主要的特点是在图片上生成当前月的日历信息。
工具和桌面设置壁纸后的效果如下:
在图片上画日历的类代码Calendar.cs如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;namespace SetWallpaper
{public class Calendar{/// <summary>/// 计算星期几: 星期日至星期六的值为0-6/// </summary>public static int GetWeeksOfDate(int year, int month, int day){DateTime dt = new DateTime(year, month, day);DayOfWeek d = dt.DayOfWeek;return Convert.ToInt32(d);} /// <summary>/// 获取指定年月的天数/// </summary>public static int GetDaysOfMonth(int year, int month){DateTime dtCur = new DateTime(year, month, 1);int days = dtCur.AddMonths(1).AddDays(-1).Day;return days;}/// <summary>/// 获取在图片上生成日历的图片/// </summary>public static Bitmap GetCalendarPic(Image img){Bitmap bmp = new Bitmap(img.Width, img.Height, PixelFormat.Format24bppRgb);bmp.SetResolution(72, 72);using (Graphics g = Graphics.FromImage(bmp)){ g.DrawImage(img, 0, 0, img.Width, img.Height); DateTime dtNow = DateTime.Now;int year = dtNow.Year;int month = dtNow.Month;int day = dtNow.Day;int day1st = Calendar.GetWeeksOfDate(year, month, 1); //第一天星期几int days = Calendar.GetDaysOfMonth(year, month); //获取想要输出月份的天数int startX = img.Width / 2; //开始的X轴位置int startY = img.Height / 4; //开始的Y轴位置int posLen = 50; //每次移动的位置长度int x = startX + day1st * posLen; //1号的开始X轴位置int y = startY + posLen * 2;//1号的开始Y轴位置Calendar.DrawStr(g, dtNow.ToString("yyyy年MM月dd日"), startX, startY);string[] weeks = { "日", "一", "二", "三", "四", "五", "六" };for (int i = 0; i < weeks.Length; i++)Calendar.DrawStr(g, weeks[i], startX + posLen * i, startY + posLen);for (int j = 1; j <= days; j++){if (j == day)//如果是今天,设置背景色Calendar.DrawStrToday(g, j.ToString().PadLeft(2, ' '), x, y);elseCalendar.DrawStr(g, j.ToString().PadLeft(2, ' '), x, y);//星期六结束到星期日时换行,X轴回到初始位置,Y轴增加if ((day1st + j) % 7 == 0){x = startX;y = y + posLen;}elsex = x + posLen;}return bmp;}}/// <summary>/// 绘制字符串/// </summary>public static void DrawStr(Graphics g, string s, float x, float y){Font font = new Font("宋体", 25, FontStyle.Bold);PointF pointF = new PointF(x, y);g.DrawString(s, font, new SolidBrush(Color.Yellow), pointF);}/// <summary>/// 绘制有背景颜色的字符串/// </summary>public static void DrawStrToday(Graphics g, string s, float x, float y){Font font = new Font("宋体", 25, FontStyle.Bold);PointF pointF = new PointF(x, y);SizeF sizeF = g.MeasureString(s, font);g.FillRectangle(Brushes.White, new RectangleF(pointF, sizeF));g.DrawString(s, font, Brushes.Black, pointF);}/// <summary>/// 根据图片路径转为Image对象/// </summary>private Image ReturnImage(string imgPath){using (FileStream fs = File.OpenRead(imgPath)){Image img = Image.FromStream(fs);return img;}}}
}
主窗体设置壁纸等的代码FrmMain.cs如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Drawing2D;
using Microsoft.Win32;
using System.Collections;
using System.Runtime.InteropServices;
using System.Xml;
using System.Drawing.Imaging;namespace SetWallpaper
{ public partial class FrmMain : Form{[DllImport("user32.dll", CharSet = CharSet.Auto)]public static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);int screenWidth = Screen.PrimaryScreen.Bounds.Width;int screenHeight = Screen.PrimaryScreen.Bounds.Height; FileInfo[] picFiles;public FrmMain(){InitializeComponent(); }private void FrmMain_Load(object sender, EventArgs e){List<DictionaryEntry> list = new List<DictionaryEntry>(){new DictionaryEntry(1, "居中显示"),new DictionaryEntry(2, "平铺显示"),new DictionaryEntry(3, "拉伸显示")};cbWallpaperStyle.DisplayMember = "Value";cbWallpaperStyle.ValueMember = "Key";cbWallpaperStyle.DataSource = list;txtPicDir.Text = XmlNodeInnerText("");timer1.Tick += new EventHandler(timer_Tick);Text = string.Format("设置桌面壁纸(当前电脑分辨率{0}×{1})", screenWidth, screenHeight);} /// <summary>/// 浏览单个图片/// </summary>private void btnBrowse_Click(object sender, EventArgs e){using (OpenFileDialog openFileDialog = new OpenFileDialog()){openFileDialog.Filter = "Images (*.BMP;*.JPG)|*.BMP;*.JPG;";openFileDialog.AddExtension = true;openFileDialog.RestoreDirectory = true;if (openFileDialog.ShowDialog() == DialogResult.OK){Bitmap img = (Bitmap)Bitmap.FromFile(openFileDialog.FileName);pictureBox1.Image = img;string msg = (img.Width != screenWidth || img.Height != screenHeight) ? ",建议选择和桌面分辨率一致图片" : "";lblStatus.Text = string.Format("当前图片分辨率{0}×{1}{2}", img.Width, img.Height, msg);}}}/// <summary>/// 手动设置壁纸/// </summary>private void btnSet_Click(object sender, EventArgs e){if (pictureBox1.Image == null){MessageBox.Show("请先选择一张图片。");return;}Image img = pictureBox1.Image; SetWallpaper(img);}private void SetWallpaper(Image img){Bitmap bmp = Calendar.GetCalendarPic(img);string filename = Application.StartupPath + "/wallpaper.bmp";bmp.Save(filename, ImageFormat.Bmp);string tileWallpaper = "0";string wallpaperStyle = "0";string selVal = cbWallpaperStyle.SelectedValue.ToString();if (selVal == "1")tileWallpaper = "1";else if (selVal == "2")wallpaperStyle = "2";//写到注册表,避免系统重启后失效RegistryKey regKey = Registry.CurrentUser;regKey = regKey.CreateSubKey("Control Panel\\Desktop");//显示方式,居中:0 0, 平铺: 1 0, 拉伸: 0 2regKey.SetValue("TileWallpaper", tileWallpaper);regKey.SetValue("WallpaperStyle", wallpaperStyle);regKey.SetValue("Wallpaper", filename);regKey.Close();SystemParametersInfo(20, 1, filename, 1);}/// <summary>/// 浏览文件夹/// </summary>private void btnBrowseDir_Click(object sender, EventArgs e){string defaultfilePath = XmlNodeInnerText("");using (FolderBrowserDialog dialog = new FolderBrowserDialog()){if (defaultfilePath != "") dialog.SelectedPath = defaultfilePath; if (dialog.ShowDialog() == DialogResult.OK) XmlNodeInnerText(dialog.SelectedPath);txtPicDir.Text = dialog.SelectedPath;}} /// <summary>/// 获取或设置配置文件中的选择目录/// </summary>/// <param name="text"></param>/// <returns></returns>public string XmlNodeInnerText(string text){string filename = Application.StartupPath + "/config.xml";XmlDocument doc = new XmlDocument();if (!File.Exists(filename)){XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null);doc.AppendChild(dec); XmlElement elem = doc.CreateElement("WallpaperPath");elem.InnerText = text;doc.AppendChild(elem);doc.Save(filename);}else{doc.Load(filename);XmlNode node = doc.SelectSingleNode("//WallpaperPath");if (node != null){if (string.IsNullOrEmpty(text))return node.InnerText;else{node.InnerText = text;doc.Save(filename);}}}return text;} /// <summary>/// 定时自动设置壁纸/// </summary>private void btnAutoSet_Click(object sender, EventArgs e){string path = txtPicDir.Text;if (!Directory.Exists(path)){MessageBox.Show("选择的文件夹不存在");return;}DirectoryInfo dirInfo = new DirectoryInfo(path);picFiles = dirInfo.GetFiles("*.jpg");if (picFiles.Length == 0){MessageBox.Show("选择的文件夹里面没有图片");return;}if (btnAutoSet.Text == "开始"){timer1.Start();btnAutoSet.Text = "停止";lblStatus.Text = string.Format("定时自动换壁纸中..."); }else{timer1.Stop();btnAutoSet.Text = "开始";lblStatus.Text = "";}}/// <summary>/// 定时随机设置壁纸/// </summary>private void timer_Tick(object sender, EventArgs e){ timer1.Interval = 1000 * 60 * (int)numericUpDown1.Value;FileInfo[] files = picFiles;if (files.Length > 0){Random random = new Random();int r = random.Next(1, files.Length);Bitmap img = (Bitmap)Bitmap.FromFile(files[r].FullName); pictureBox1.Image = img;SetWallpaper(img);}}/// <summary>/// 双击托盘图标显示窗体/// </summary>private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e){ShowForm();}/// <summary> /// 隐藏窗体,并显示托盘图标 /// </summary> private void HideForm(){this.Visible = false;this.WindowState = FormWindowState.Minimized;notifyIcon1.Visible = true;}/// <summary> /// 显示窗体 /// </summary> private void ShowForm(){this.Visible = true;this.WindowState = FormWindowState.Normal;notifyIcon1.Visible = false;}private void ToolStripMenuItemShow_Click(object sender, EventArgs e){ShowForm();}/// <summary> /// 退出 /// </summary> private void toolStripMenuItemExit_MouseDown(object sender, MouseEventArgs e){
if (MessageBox.Show("您确认要退出吗?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
this.Dispose();//一定要加这行,否则会弹出2次确认框
Application.Exit();
}}/// <summary> /// 最小化时隐藏窗体,并显示托盘图标 /// </summary> private void FrmMain_SizeChanged(object sender, EventArgs e){if (this.WindowState == FormWindowState.Minimized){HideForm();}}
private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("您确认要退出吗?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
this.Dispose();//一定要加这行,否则会弹出2次确认框
Application.Exit();
}
else
e.Cancel = true;
}}
}
备注:
应用程序最小化图标显示在任务栏并可鼠标右击菜单显示和退出,上面包括了后台代码,前台设计界面的布置如下:
1、双击工具箱 contextMenuStrip 控件,设置如下:
①属性Name = "contextMenuStrip1";
②属性Items集合中添加两个MenuItem菜单项:
菜单1设置Name = "ToolStripMenuItemShow"、Text = "显示"
菜单2设置Name = "toolStripMenuItemExit"、Text = "退出"
③菜单项ToolStripMenuItemShow 关联事件ToolStripMenuItemShow_Click;
④菜单项toolStripMenuItemExit 关联事件toolStripMenuItemExit.MouseDown;
2、双击工具箱 notifyIcon 控件,设置如下:
①属性ContextMenuStrip = "contextMenuStrip1"
②属性Text = "设置桌面壁纸"
③属性Icon:选择一个本地图标文件
④关联事件notifyIcon1_MouseDoubleClick
完整的项目代码下载:
http://download.csdn.net/detail/gdjlc/5096674
winform壁纸工具:为图片添加当月的日历并设为壁纸相关推荐
- python 日历壁纸_winform壁纸工具:为图片添加当月的日历并设为壁纸 .
这几天用winform做了一个设置壁纸的小工具, 为图片添加当月的日历并设为壁纸,可以手动设置壁纸,也可以定时设置壁纸,最主要的特点是在图片上生成当前月的日历信息. 工具和桌面设置壁纸后的效果如下: ...
- 如何使用DW工具给图片添加热点
一.准备一张图片 准备一张需要给不同区域添加不同热点的图片 二.插入图片 三.找到地图工具: 单击鼠标左键点击图片,这时候软件下方的属性面板就会变成和图片相关的属性,注意看左下角部分,如图一中 ...
- C#窗体Winform,如何嵌入图片添加图片,使用图片资源?
1.首先,打开工具箱,找到PictureBox控件 2.打开PictureBox的属性面板,设置Image属性 3.准备嵌入图片资源 图片资源有两个地方,一个是全局的在Properties下的Reso ...
- 图片添加边框工具:AKVIS ArtSuite for Mac
你也想为你的图片添加各种精美的边框吗?akvis artsuite mac破解版是一款用于装饰照片的工具,可以非常方便的为照片或者图片添加上精美的相框或者边框!程序可独立运行,也可以作为Photosh ...
- Winform水印工具(文字和图片皆可)
Winform水印工具(文字和图片皆可) 简介:如题Winform水印工具,原图和水印图都将以缩略图的形式展示在工具上 水印类型/水印内容:文字.图片 水印位置:左上角.右上角.居中.左下角.右下角 ...
- java制作海报工具类,java操作图片贴图,java给图片添加文字,调整字体颜色大小间距
工具类 java操作图片,给一个大图片贴小图片,给图片添加文字并调整文字颜色,大小,字体间距,把本地图片或者网络图片加载到缓冲区 主要方法: imageIoRead方法,把图片加载到缓冲区 merge ...
- 视频剪辑工具,图片批量添加背景,支持图片、视频背景
最近有很多朋友在问,如何批量给图片添加背景呢?而且是加图片或者视频的那种呢?不知道如何操作的宝贝们,下面请随小编一起来试试吧. 需要哪些工具? 视频素材若干 怎么快速剪辑? 运行[媒体梦工厂],在&q ...
- Java 图片添加数字暗水印工具类
Java 图片添加数字暗水印工具类. package cnki.thesis.common.utils;import org.opencv.core.*;import java.util.ArrayL ...
- C#WinForm开发:如何将图片添加到项目资源文件(Resources)中
C#WinForm开发:如何将图片添加到项目资源文件(Resources)中 引言 操作步骤 实例应用 功能延展 引言 在C#Winform开发中,有时需要在控件中插入一些图片,常见的有picture ...
最新文章
- ADO与ADO.NET
- python读取json配置文件_Python简单读取json文件功能示例
- web前端开发最佳实践--(笔记之JavaScript最佳实践)
- 前端学习(601):集成react插件
- pycharm python InvalidVersionSpecError: Invalid version spec: =2.7
- UVA 10791 Minimum Sum LCM 数论
- 用户故事与敏捷方法笔记---估算用户故事
- 正确姿势使用TraceView工具
- 全网通小区专家全自动做
- LintCode 交叉字符串
- HTML5 WebSockets 基础使用教程
- 实际使用Windows 7中的Readyboost功能
- ubuntu 20.04 不能鼠标双击打开 .desktop (桌面快捷方式图标)文件(双击变为使用文本编辑器打开)的解决办法
- antony.net
- 粒子群算法的matlab动态图显示 实现(一)
- 【leetcode】1419. Minimum Number of Frogs Croaking
- (dfppy)2Ir(NHC)的蓝光/蓝绿光铱配合物|苯基喹啉酯的中性铱配合物-齐岳生物
- 研究生看文献时如何写读书笔记?
- linux启动mysql1820_linux下安装mysql的问题解决
- redis watch使用场景_redis使用watch完成秒杀抢购
热门文章
- 思想——坚定不移的信仰
- 服务器网站环境包,使用wips网站环境包的案例
- Spark RDD算子(八)mapPartitions, mapPartitionsWithIndex
- linux crash,系统崩溃 - crash工具介绍
- pjsip 屏幕直播
- 我的涨分日记(二)——BestCoder Round #59
- Android 仿微信多语言切换
- 好东东-汉语词法分析系统ICTCLAS (Institute of Computing Technology, Chinese Lexical Analysis System)
- 微信小程序汽车租赁平台+后台管理系统
- c语言写字符舞蹈,C语言实现舞伴问题