winform壁纸工具为图片添加当前月的日历信息

 更新时间:2020年6月25日 11:43  点击:1510
这几天用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);
else
Calendar.DrawStr(g, j.ToString().PadLeft(2, ' '), x, y);
//星期六结束到星期日时换行,X轴回到初始位置,Y轴增加
if ((day1st + j) % 7 == 0)
{
x = startX;
y = y + posLen;
}
else
x = 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);
}
}
}

主窗体设置壁纸等的代码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 2
regKey.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)
{
Application.Exit();
}
/// <summary>
/// 最小化时隐藏窗体,并显示托盘图标
/// </summary>
private void FrmMain_SizeChanged(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
{
HideForm();
}
}
}
}
[!--infotagslink--]

相关文章

  • 华为Mate9原装高清壁纸合集:分辨率超赞

    华为日前在德国慕尼黑正式发布了新一代旗舰Mate 9,但其实早在9月底,Mate 9的两个版本就通过了工信部审核,只是没有照片,在等待的日子里,Mate 9原装高清壁纸已经提前出炉了,总共有20张,有兴趣的朋友可以收藏一下哦...2016-12-15
  • Jquery日历插件制作简单日历

    在页面开发中,经常遇到需要用户输入日期的操作。通常的做法是,提供一个文本框(text),让用户输入,然后,编写代码验证输入的数据,检测其是否是日期类型。这样比较麻烦,同时,用户输入日期的操作也不是很方便,影响用户体验。如果使...2015-10-30
  • php简单日历函数

    本文实例讲述了php实现的日历程序。分享给大家供大家参考。具体如下:<&#63;php /* * php 输出日历程序 */ header("Content-type: text/html;charset=utf-8"); $year=(!isset($_GET['year'])||$_GET['year']=="")&#63;...2015-10-30
  • 教大家制作简单的php日历

    最近的一个项目中,需要将数据用日历方式显示,网上有很多的JS插件,后面为了自己能有更大的控制权,决定自己制作一个日历显示。如下图所示:一、计算数据 1、new一个Calendar类2、初始化两个下拉框中的数据,年份与月份3、初始...2015-11-24
  • C#实现农历日历的方法

    这篇文章主要介绍了C#实现农历日历的方法,详细分析了使用C#实现农历日历的完整步骤,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25
  • 一起学写js Calender日历控件

    这篇文章主要和大家一起学写js Calender控件,自己动手编写了一个简易日历控件,感兴趣的小伙伴们可以参考一下...2016-04-17
  • php简单日历函数

    本文实例讲述了php实现的日历程序。分享给大家供大家参考。具体如下:<&#63;php /* * php 输出日历程序 */ header("Content-type: text/html;charset=utf-8"); $year=(!isset($_GET['year'])||$_GET['year']=="")&#63;...2015-10-30
  • JavaScript制作简单的日历效果

    这篇文章主要为大家介绍了JavaScript制作简单的日历效果实现代码,感兴趣的小伙伴们可以参考一下...2016-03-12
  • ASP.NET Calendar日历(日期)控件使用方法

    本文主要介绍Calendar日历控件的各个属性以及举例演示Calendar控件的具体使用方法,希望对大家有所帮助。...2021-09-22
  • C#实现功能强大的中国农历日历操作类

    这篇文章主要介绍了C#实现功能强大的中国农历日历操作类,实例分析了C#操作时间及字符串的技巧,非常具有实用价值,需要的朋友可以参考下...2020-06-25
  • C语言打印某一年的日历

    这篇文章主要为大家详细介绍了C语言打印某一年的日历,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-06-14
  • ASP.NET中实现弹出日历示例

    这篇文章介绍了ASP.NET弹出日历功能的实现方法,有需要的朋友可以参考一下。...2021-09-22
  • 基于jquery实现日历效果

    这篇文章主要为大家详细介绍了基于jquery实现日历效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-03-14
  • PHP简单日历实例

    <?php /* * PHP简单日历实例 * 作者: 多菜鸟 * 邮箱: kingerq AT msn DOT com * 来源: http://blog.111cn.net/kingerq/ * 创建时间: 2008-01-03 **/ $...2016-11-25
  • asp.net基于Calendar实现blog日历功能示例

    这篇文章主要介绍了asp.net基于Calendar实现blog日历功能,涉及asp.net使用Calendar控件操作日期与时间相关运算技巧,需要的朋友可以参考下...2021-09-22
  • php简单日历实现程序代码

    关于日历的应用,应该在独立博客上面能很好的体现出来吧,不管是 php 的 wp 博客,还是 ASP 的 z_blog 博客,都应用了日历的功能,那就是日志存档了,在我们要看以前发布的日志时...2016-11-25
  • js编写当天简单日历效果【实现代码】

    下面小编就为大家带来一篇js编写当天简单日历效果【实现代码】。小编觉得挺不错的,现在分享给大家,也给大家做个参考...2016-05-05
  • javascript html实现网页版日历代码

    这篇文章主要介绍了javascript html实现网页版日历代码,需要的朋友可以参考下...2016-03-10
  • Illustrator绘制可以翻页的日历图标教程

    今天小编在这里就来给Illustrator的这一款软件的使用者们来说一说绘制可以翻页的日历图标的教程,各位想知道具体绘制方法的使用者们,那么下面就快来跟着小编一起看看吧...2016-09-14
  • Android实现系统日历同步日程

    这篇文章主要为大家详细介绍了Android实现系统日历同步日程,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-04-27