Winform wallpaper tool adds calendar information for the current month to the image

Source: Internet
Author: User

In the past few days, winform has been used as a small tool for wallpaper setting. You can add the calendar of the current month to the image and set it as a wallpaper. You can manually set the wallpaper or set it regularly, the main feature is to generate calendar information for the current month on the image.

After setting the wallpaper for tools and desktops, the effects are as follows:

The Calendar class code Calendar. cs is as follows:Copy codeThe Code is as follows: 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>
/// Calculate the day of the week: the value from Sunday to Saturday is 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>
/// Obtain the number of days in a specified year.
/// </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>
/// Obtain the calendar generated on the Image
/// </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); // the day of the week on the first day
Int days = Calendar. GetDaysOfMonth (year, month); // gets the number of days of the month to be output
Int startX = img. Width/2; // The starting X axis position.
Int startY = img. Height/4; // start y axis position
Int posLen = 50; // The length of each moving position
Int x = startX + day1st * posLen; // The start x axis position of No. 1
Int y = startY + posLen * 2; // start y-axis position of No. 1
Calendar. DrawStr (g, dtNow. ToString ("MM dd, yyyy"), startX, startY );
String [] weeks = {"day", "1", "2", "3", "4", "5", "6 "};
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) // if it is today, set the background color
Calendar. DrawStrToday (g, j. ToString (). PadLeft (2, ''), x, y );
Else
Calendar. DrawStr (g, j. ToString (). PadLeft (2, ''), x, y );
// Wrap the line from the end of Saturday to Sunday, return the X axis to the initial position, and increase the Y axis.
If (day1st + j) % 7 = 0)
{
X = startX;
Y = y + posLen;
}
Else
X = x + posLen;
}
Return bmp;
}
}
/// <Summary>
/// Draw a string
/// </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>
/// Draw a string with background color
/// </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 );
}
}
}

The Code FrmMain. cs for setting wallpaper in the main form is as follows:Copy codeThe Code is as follows: 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, "center display "),
New DictionaryEntry (2, "tiled display "),
New DictionaryEntry (3, "Stretch display ")
};
CbWallpaperStyle. DisplayMember = "Value ";
CbWallpaperStyle. ValueMember = "Key ";
CbWallpaperStyle. DataSource = list;
TxtPicDir. Text = XmlNodeInnerText ("");
Timer1.Tick + = new EventHandler (timer_Tick );
Text = string. Format ("set desktop wallpaper (current computer resolution: {0} × {1})", screenWidth, screenHeight );
}
/// <Summary>
/// Browse a single image
/// </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 )? ", We recommend that you select the same image as the desktop resolution ":"";
LblStatus. Text = string. Format ("current image resolution: {0} × {1} {2}", img. Width, img. Height, msg );
}
}
}
/// <Summary>
/// Manually set the wallpaper
/// </Summary>
Private void btnSet_Click (object sender, EventArgs e)
{
If (pictureBox1.Image = null)
{
MessageBox. Show ("select an image first. ");
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 ";
// Write to the registry to prevent system failure after restart
RegistryKey regKey = Registry. CurrentUser;
RegKey = regKey. CreateSubKey ("Control Panel \ Desktop ");
// Display mode, center: 0 0, tile: 1 0, stretch: 0 2
RegKey. SetValue ("TileWallpaper", tileWallpaper );
RegKey. SetValue ("WallpaperStyle", wallpaperStyle );
RegKey. SetValue ("Wallpaper", filename );
RegKey. Close ();
SystemParametersInfo (20, 1, filename, 1 );
}
/// <Summary>
/// Browse folders
/// </Summary>
Private void btnBrowseDir_Click (object sender, EventArgs e)
{
String defaultfilePath = XmlNodeInnerText ("");
Using (FolderBrowserDialog dialog = new FolderBrowserDialog ())
{
If (defafilefilepath! = "")
Dialog. SelectedPath = defaultfilePath;
If (dialog. ShowDialog () = DialogResult. OK)
XmlNodeInnerText (dialog. SelectedPath );
TxtPicDir. Text = dialog. SelectedPath;
}
}
/// <Summary>
/// Obtain or set the selection directory in the configuration file
/// </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>
/// Automatically set wallpaper at regular intervals
/// </Summary>
Private void btnAutoSet_Click (object sender, EventArgs e)
{
String path = txtPicDir. Text;
If (! Directory. Exists (path ))
{
MessageBox. Show ("the selected folder does not exist ");
Return;
}
DirectoryInfo dirInfo = new DirectoryInfo (path );
PicFiles = dirInfo. GetFiles ("*. jpg ");
If (picFiles. Length = 0)
{
MessageBox. Show ("no image in the selected folder ");
Return;
}
If (btnAutoSet. Text = "")
{
Timer1.Start ();
BtnAutoSet. Text = "stop ";
LblStatus. Text = string. Format ("Regular automatic wallpaper replacement ...");
}
Else
{
Timer1.Stop ();
BtnAutoSet. Text = "";
LblStatus. Text = "";
}
}
/// <Summary>
/// Set wallpaper randomly at regular intervals
/// </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>
/// Double-click the tray icon to display the form
/// </Summary>
Private void policyicon#mousedoubleclick (object sender, MouseEventArgs e)
{
ShowForm ();
}
/// <Summary>
/// Hide the form and display the tray icon
/// </Summary>
Private void HideForm ()
{
This. Visible = false;
This. WindowState = FormWindowState. Minimized;
Policyicon1.visible = true;
}
/// <Summary>
/// Display form
/// </Summary>
Private void ShowForm ()
{
This. Visible = true;
This. WindowState = FormWindowState. Normal;
Policyicon1.visible = false;
}
Private void ToolStripMenuItemShow_Click (object sender, EventArgs e)
{
ShowForm ();
}
/// <Summary>
/// Exit
/// </Summary>
Private void toolStripMenuItemExit_MouseDown (object sender, MouseEventArgs e)
{
Application. Exit ();
}
/// <Summary>
/// Hide the form and display the tray icon when minimized
/// </Summary>
Private void FrmMain_SizeChanged (object sender, EventArgs e)
{
If (this. WindowState = FormWindowState. Minimized)
{
HideForm ();
}
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.