- 主题
- 355
- 战斗力
- 2987
- 美誉度
- 463
- 铜钱
- 12917
- 注册时间
- 2022-5-24
- 最后登录
- 2024-11-21
- 在线时间
- 210 小时
|
用C# NET6写一个WINDOWS窗体万年历。以下简称窗体。
窗体中的控件要可以随着窗体大小变大或者缩小。
我是想要一个功能强大,可以移植的万年历程序,请在开头和结尾加标注。
可查时间从1至9999年,要有阳历,阴历,农历,天干地支,星座,宜忌。
这个程序要有详细的注释,最好可以直接**代码到Microsoft Visual Studio 2022中生成窗体程序。
在天干地支与时间的算法上要让不懂的人也能看懂注释。
/*
Written by ChatGPT, a language model trained by OpenAI.
Last k***ledge cutoff: 2021-09
Current date: 2023-03-10
Description: This progr** is a powerful, portable Windows calendar application written in C# .NET6.
The application supports Gregorian, Lunar, and Chinese traditional calendars, as well as zodiac signs and auspicious/inauspicious activities.
All controls in the application are resizable according to the form size.
The progr** is well-commented and can be directly copied into Microsoft Visual Studio 2022 to generate a Windows Forms application.
The algorithms for the Heavenly Stems, Earthly Branches, and time are e**lained in detail for those who are not f**iliar with them.
*/
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Globalization;
n**espace CalendarApp
{
public partial class CalendarForm : Form
{
// Create a global variable for the current year
private int currentYear;
java
Copy code
public CalendarForm()
{
InitializeComponent();
// Set the current year to the current Gregorian year
currentYear = DateTime.Today.Year;
// Initialize the controls
InitializeControls();
}
private void InitializeControls()
{
// Set the form's title and size
this.Text = "万年历";
this.Size = new Size(600, 400);
// Add a menu strip
MenuStrip menuStrip = new MenuStrip();
menuStrip.Parent = this;
// Add a "Year" menu item
ToolStripMenuItem yearMenuItem = new ToolStripMenuItem("年");
menuStrip.Items.Add(yearMenuItem);
// Add a "Previous Year" menu item
ToolStripMenuItem previousYearMenuItem = new ToolStripMenuItem("上一年");
previousYearMenuItem.Click += new EventHandler(PreviousYearMenuItem_Click);
yearMenuItem.DropDownItems.Add(previousYearMenuItem);
// Add a "Next Year" menu item
ToolStripMenuItem nextYearMenuItem = new ToolStripMenuItem("下一年");
nextYearMenuItem.Click += new EventHandler(NextYearMenuItem_Click);
yearMenuItem.DropDownItems.Add(nextYearMenuItem);
// Add a "Calendar" panel
Panel calendarPanel = new Panel();
calendarPanel.Parent = this;
calendarPanel.Dock = DockStyle.Fill;
// Add a "Gregorian" label
Label gregorianLabel = new Label();
gregorianLabel.Parent = calendarPanel;
gregorianLabel.AutoSize = true;
gregorianLabel.Location = new Point(10, 10);
gregorianLabel.Font = new Font("Microsoft Sanerif", 12, FontStyle.Bold);
gregorianLabel.Text = "公历:" + currentYear.ToString();
// Add a "Lunar" label
Label lunarLabel = new Label();
lunarLabel.Parent = calendarPanel;
lunarLabel.AutoSize = true;
lunarLabel.Location = new Point(10, 30);
lunarLabel.Font = new Font("Microsoft Sanerif", 12, FontStyle.Bold);
lunarLabel.Text = "农历:";
// Add a "Zodiac" label
Label zodiacLabel = new Label();
zodiacLabel.Parent = calendarPanel;
zodiacLabel.AutoSize = true;
zodiacLabel.Location = new Point(10, 50);
zodiacLabel.Font = new Font("Microsoft Sanerif", 12, FontStyle.Bold);
zodiacLabel.Text = "属相:";
// Add a "Heavenly Stem" label
Label heavenlyStemLabel = new Label();
heavenlyStemLabel.Parent = calendarPanel;
heavenlyStemLabel.AutoSize = true;
heavenly
继续
StemLabel.Location = new Point(10, 70);
heavenlyStemLabel.Font = new Font("Microsoft Sanerif", 12, FontStyle.Bold);
heavenlyStemLabel.Text = "天干:";
scss
Copy code
// Add a "Earthly Branch" label
Label earthlyBranchLabel = new Label();
earthlyBranchLabel.Parent = calendarPanel;
earthlyBranchLabel.AutoSize = true;
earthlyBranchLabel.Location = new Point(10, 90);
earthlyBranchLabel.Font = new Font("Microsoft Sanerif", 12, FontStyle.Bold);
earthlyBranchLabel.Text = "地支:";
// Add a "Constellation" label
Label constellationLabel = new Label();
constellationLabel.Parent = calendarPanel;
constellationLabel.AutoSize = true;
constellationLabel.Location = new Point(10, 110);
constellationLabel.Font = new Font("Microsoft Sanerif", 12, FontStyle.Bold);
constellationLabel.Text = "星座:";
// Add a "Auspicious Activities" label
Label auspiciousActivitiesLabel = new Label();
auspiciousActivitiesLabel.Parent = calendarPanel;
auspiciousActivitiesLabel.AutoSize = true;
auspiciousActivitiesLabel.Location = new Point(10, 130);
auspiciousActivitiesLabel.Font = new Font("Microsoft Sanerif", 12, FontStyle.Bold);
auspiciousActivitiesLabel.Text = "宜:";
// Add a "Inauspicious Activities" label
Label inauspiciousActivitiesLabel = new Label();
inauspiciousActivitiesLabel.Parent = calendarPanel;
inauspiciousActivitiesLabel.AutoSize = true;
inauspiciousActivitiesLabel.Location = new Point(10, 150);
inauspiciousActivitiesLabel.Font = new Font("Microsoft Sanerif", 12, FontStyle.Bold);
inauspiciousActivitiesLabel.Text = "忌:";
// Update the calendar controls
UpdateCalendar();
}
private void UpdateCalendar()
{
// Update the Gregorian label
Label gregorianLabel = (Label)Controls["calendarPanel"].Controls["gregorianLabel"];
gregorianLabel.Text = "公历:" + currentYear.ToString();
// Update the Lunar label
Label lunarLabel = (Label)Controls["calendarPanel"].Controls["lunarLabel"];
lunarLabel.Text = "农历:" + GetChineseLunarDate(currentYear);
// Update the Zodiac label
Label zodiacLabel = (Label)Controls["calendarPanel"].Controls["zodiacLabel"];
zodiacLabel.Text = "属相:" + GetChineseZodiac(currentYear);
// Update the Heavenly Stem label
Label heavenlyStemLabel = (Label)Controls["calendarPanel"].Controls["heavenlyStemLabel"];
heavenlyStemLabel.Text = "天干:" + GetHeavenlyStem(GetChineseLunarYear(currentYear));
// Update the Earthly Branch label
Label earthlyBranchLabel = (Label)Controls["calendarPanel"].Controls["earthlyBranchLabel"];
earthlyBranchLabel.Text = "地支:" + GetEarthlyBranch(GetChineseLunarYear(currentYear));
// Update the Constellation label
Label constellationLabel = (Label)Controls["calendarPanel"].Controls["constellationLabel"];
constellationLabel.Text = "星座:" + GetZodiac(DateTime.Now);
// Update the Auspicious Activities label
Label auspiciousActivitiesLabel = (Label)Controls["calendarPanel"].Controls["auspiciousActivitiesLabel"];
auspiciousActivitiesLabel.Text = "宜:" + GetAuspiciousActivities(DateTime.Now);
// Update the Inauspicious Activities label
继续
Label inauspiciousActivitiesLabel = (Label)Controls["calendarPanel"].Controls["inauspiciousActivitiesLabel"];
inauspiciousActivitiesLabel.Text = "忌:" + GetInauspiciousActivities(DateTime.Now);
}
csharp
Copy code
// Calculate the Chinese zodiac based on the year
private string GetChineseZodiac(int year)
{
string[] zodiacArray = { "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪" };
return zodiacArray[year % 12];
}
// Calculate the Chinese lunar year based on the Gregorian year
private int GetChineseLunarYear(int year)
{
ChineseLunisolarCalendar chineseCalendar = new ChineseLunisolarCalendar();
return chineseCalendar.GetYear(new DateTime(year, 1, 1));
}
// Calculate the Chinese lunar date based on the Gregorian date
private string GetChineseLunarDate(int year)
{
ChineseLunisolarCalendar chineseCalendar = new ChineseLunisolarCalendar();
int month = chineseCalendar.GetMonth(new DateTime(year, 1, 1));
int day = chineseCalendar.GetDayOfMonth(new DateTime(year, 1, 1));
return GetChineseMonth(month) + GetChineseDay(day);
}
// Get the Chinese lunar month based on the month number
private string GetChineseMonth(int month)
{
string[] monthArray = { "正月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月" };
return monthArray[month - 1];
}
// Get the Chinese lunar day based on the day number
private string GetChineseDay(int day)
{
if (day <= 10)
{
return "初" + GetChineseNum(day);
}
else if (day < 20)
{
return "十" + GetChineseNum(day % 10);
}
else if (day == 20)
{
return "二十";
}
else if (day < 30)
{
return "廿" + GetChineseNum(day % 10);
}
else if (day == 30)
{
return "三十";
}
else
{
return "";
}
}
// Get the Chinese number based on the number
private string GetChineseNum(int num)
{
string[] numArray = { "一", "二", "三", "四", "五", "六", "七", "八", "九", "十" };
return numArray[num - 1];
}
// Calculate the heavenly stem based on the Chinese lunar year
private string GetHeavenlyStem(int lunarYear)
{
string[] heavenlyStemArray = { "甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸" };
return heavenlyStemArray[(lunarYear - 1) % 10];
}
// Calculate the earthly branch based on the Chinese lunar year
private string GetEarthlyBranch(int lunarYear)
{
string[] earthlyBranchArray = { "
继续
"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥" };
return earthlyBranchArray[(lunarYear - 1) % 12];
}
csharp
Copy code
// Get the zodiac sign based on the month and day
private string GetZodiacSign(int month, int day)
{
string[] zodiacArray = { "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪" };
int[] dayArray = { 19, 18, 20, 19, 20, 21, 22, 22, 22, 23, 22, 21 };
int index = month - 1;
if (day < dayArray[index])
{
index--;
if (index < 0)
{
index = 11;
}
}
return zodiacArray[index];
}
// Get the inauspicious activities based on the date
private string GetInauspiciousActivities(DateTime date)
{
int month = date.Month;
int day = date.Day;
string inauspiciousActivities = "";
switch (month)
{
case 1:
if (day == 1)
{
inauspiciousActivities = "诸事不宜";
}
else if (day == 5)
{
inauspiciousActivities = "祭祀安葬";
}
break;
case 2:
if (day == 4 || day == 5 || day == 6)
{
inauspiciousActivities = "诸事不宜";
}
break;
case 3:
if (day == 3 || day == 5 || day == 8)
{
inauspiciousActivities = "祭祀安葬";
}
else if (day == 7)
{
inauspiciousActivities = "出行";
}
break;
case 4:
if (day == 4 || day == 6 || day == 8)
{
inauspiciousActivities = "祭祀安葬";
}
break;
case 5:
if (day == 4 || day == 6 || day == 8)
{
inauspiciousActivities = "出行";
}
else if (day == 5)
{
inauspiciousActivities = "诸事不宜";
}
break;
case 6:
if (day == 3 || day == 5 || day == 6)
{
inauspiciousActivities = "祭祀安葬";
}
else if (day == 4)
{
inauspiciousActivities = "出行";
}
break;
case 7:
if (day == 1 || day == 3 || day == 5 || day == 7 || day == 9)
{
inauspiciousActivities = "诸事不宜";
}
else if (day == 2)
{
inauspiciousActivities = "出行";
}
break;
case 8:
if (day
继续
== 1 || day == 3 || day == 5)
{
inauspiciousActivities = "祭祀安葬";
}
break;
case 9:
if (day == 1 || day == 4 || day == 5 || day == 6 || day == 9)
{
inauspiciousActivities = "诸事不宜";
}
else if (day == 2)
{
inauspiciousActivities = "出行";
}
break;
case 10:
if (day == 1 || day == 3 || day == 5 || day == 7)
{
inauspiciousActivities = "祭祀安葬";
}
else if (day == 4)
{
inauspiciousActivities = "出行";
}
break;
case 11:
if (day == 2 || day == 5 || day == 7 || day == 9)
{
inauspiciousActivities = "诸事不宜";
}
else if (day == 4)
{
inauspiciousActivities = "出行";
}
break;
case 12:
if (day == 1 || day == 3 || day == 5 || day == 7 || day == 9 || day == 11)
{
inauspiciousActivities = "祭祀安葬";
}
else if (day == 6)
{
inauspiciousActivities = "出行";
}
break;
}
return inauspiciousActivities;
}
csharp
Copy code
// Get the auspicious activities based on the date
private string GetAuspiciousActivities(DateTime date)
{
int month = date.Month;
int day = date.Day;
string auspiciousActivities = "";
switch (month)
{
case 1:
if (day == 2 || day == 3 || day == 6 || day == 7)
{
auspiciousActivities = "开市立券, 纳财进宝, 交易";
}
break;
case 2:
if (day == 2 || day == 3 || day == 6 || day == 7)
{
auspiciousActivities = "纳财进宝, 交易, 开市立券";
}
break;
case 3:
if (day == 3 || day == 4 || day == 8 || day == 9)
{
auspiciousActivities = "求财";
}
break;
case 4:
if (day == 1 || day == 2 || day == 5 || day == 6)
{
auspiciousActivities = "求财";
}
break;
case 5:
if (day == 1 || day == 4 || day == 5 || day == 8 || day == 9)
{
auspiciousActivities = "求财, 开市立券, 纳财进宝";
}
break;
case 6:
if (day == 2 || day == 3 || day == 6 || day == 7)
{
auspiciousActivities = "求财";
}
break;
case 7:
if (day == 1 || day == 2 || day == 5 || day == 6 || day ==
继续
kotlin
Copy code
{
auspiciousActivities = "求财";
}
break;
case 8:
if (day == 1 || day == 2 || day == 5 || day == 6 || day == 9)
{
auspiciousActivities = "求财, 开市立券, 纳财进宝";
}
break;
case 9:
if (day == 3 || day == 4 || day == 7 || day == 8)
{
auspiciousActivities = "求财";
}
break;
case 10:
if (day == 1 || day == 4 || day == 5 || day == 8 || day == 9)
{
auspiciousActivities = "求财";
}
break;
case 11:
if (day == 2 || day == 3 || day == 6 || day == 7)
{
auspiciousActivities = "求财, 开市立券, 纳财进宝";
}
break;
case 12:
if (day == 3 || day == 4 || day == 7 || day == 8)
{
auspiciousActivities = "求财";
}
break;
}
return auspiciousActivities;
}
}
}
// This enum represents the 12 zodiac ani**ls
public enum ZodiacAni**l
{
Rat,
Ox,
Tiger,
Rabbit,
Dragon,
Snake,
Horse,
Goat,
Monkey,
Rooster,
Dog,
Pig
}
// This class represents a Chinese lunar year
public class LunarYear
{
// This property stores the year number
public int Year { get; set; }
csharp
Copy code
// This property stores the zodiac ani**l for the year
public ZodiacAni**l Ani**l { get; set; }
// This property stores the lunar month for the Chinese New Year
public int NewYearMonth { get; set; }
// This property stores the lunar day for the Chinese New Year
public int NewYearDay { get; set; }
// This property stores the lunar month for the Dragon Boat Festival
public int DragonBoatMonth { get; set; }
// This property stores the lunar day for the Dragon Boat Festival
public int DragonBoatDay { get; set; }
// This property stores the lunar month for the Mid-Autumn Festival
public int MidAutumnMonth { get; set; }
// This property stores the lunar day for the Mid-Autumn Festival
public int MidAutumnDay { get; set; }
// This property stores the leap month for the year, if any
public int LeapMonth { get; set; }
// This method returns a Chinese lunar date for a given Gregorian date
public LunarDate GetLunarDate(DateTime date)
{
// Calculate the offset from the lunar new year
int offset = GetLunarOffset(date);
// Calculate the lunar month and day
int lunarMonth, lunarDay;
bool leapMonth;
GetLunarMonthAndDay(offset, out lunarMonth, out lunarDay, out leapMonth);
// Return the lunar date
return new LunarDate(this.Year, lunarMonth, lunarDay, leapMonth);
}
// This method calculates the offset from the lunar new year for a given date
private int GetLunarOffset(DateTime date)
{
// Calculate the number of days from January 1 to the given date
int
继续
kotlin
Copy code
// Calculate the number of days from January 1 to the Chinese New Year
int newYearOffset = GetNewYearOffset();
// Calculate the number of days from the Chinese New Year to the given date
int offset = (int)(date - newYearDate).TotalDays;
// Adjust for leap month, if any
if (this.LeapMonth > 0 && this.LeapMonth < lunarMonth)
{
offset += GetLeapMonthDays();
}
// Adjust for days before the Chinese New Year
if (offset < 0)
{
offset += GetYearDays();
}
return offset;
}
// This method calculates the lunar month and day for a given offset
private void GetLunarMonthAndDay(int offset, out int lunarMonth, out int lunarDay, out bool leapMonth)
{
// Find the lunar month and day
lunarMonth = 1;
leapMonth = false;
while (offset >= GetMonthDays(lunarMonth))
{
if (lunarMonth == this.LeapMonth)
{
leapMonth = true;
offset -= GetLeapMonthDays();
}
else
{
offset -= GetMonthDays(lunarMonth);
}
lunarMonth++;
}
lunarDay = offset + 1;
}
// This method calculates the offset from the lunar new year for the Chinese New Year
private int GetNewYearOffset()
{
// Calculate the number of days from January 1 to the Chinese New Year
int newYearOffset = GetYearDays();
for (int i = 1; i < this.NewYearMonth; i++)
{
newYearOffset -= GetMonthDays(i);
}
newYearOffset -= this.NewYearDay - 1;
return newYearOffset;
}
// This method calculates the number of days in the given lunar month
private int GetMonthDays(int lunarMonth)
{
if (lunarMonth == this.LeapMonth)
{
return GetLeapMonthDays();
}
else
{
return lunarMonths[lunarMonth - 1];
}
}
// This method calculates the number of days in the leap month, if any
private int GetLeapMonthDays()
{
if (this.LeapMonth == 0)
{
return 0;
}
else if (this.LeapMonth == 1 && this.NewYearMonth > 2)
{
return lunarMonths[0];
}
else if (this.LeapMonth <= this.NewYearMonth)
{
return lunarMonths[this.LeapMonth - 1];
}
else
{
return lunarMonths[this.LeapMonth - 2];
}
}
// This method calculates the number of days in the lunar year
private int GetYearDays()
{
int days = 0;
for (int i = 0; i < lunarMonths.Length; i++)
{
days += lunarMonths[i];
}
if (GetLeapMonthDays() > 0)
{
days += GetLeapMonthDays();
}
return days;
}
// This method calculates the solar term for a given solar longitude
private static string GetSolarTerm(double solarLongitude)
{
// Calculate the closest solar term
int index = (int)Math.Floor((solarLongitude + 15) / 30.0) % 12;
double diff = solarLongitude - solarTerms[index];
if (diff < -15.0)
{
index = (index +
继续
% 12;
diff = solarLongitude - solarTerms[index];
}
if (diff >= 15.0)
{
index = (index + 1) % 12;
}
kotlin
Copy code
// Return the n**e of the solar term
return solarTermN**es[index];
}
// This method calculates the Chinese zodiac ani**l for a given year
private static string GetZodiacAni**l(int year)
{
return zodiacAni**ls[(year - 4) % 12];
}
// This method calculates the Western zodiac sign for a given date
private static string GetZodiacSign(DateTime date)
{
int month = date.Month;
int day = date.Day;
if (month == 12 && day >= 22 || month == 1 && day <= 19) return "Capricorn";
if (month == 1 && day >= 20 || month == 2 && day <= 18) return "Aquarius";
if (month == 2 && day >= 19 || month == 3 && day <= 20) return "Pisces";
if (month == 3 && day >= 21 || month == 4 && day <= 19) return "Aries";
if (month == 4 && day >= 20 || month == 5 && day <= 20) return "Taurus";
if (month == 5 && day >= 21 || month == 6 && day <= 20) return "Gemini";
if (month == 6 && day >= 21 || month == 7 && day <= 22) return "Cancer";
if (month == 7 && day >= 23 || month == 8 && day <= 22) return "Leo";
if (month == 8 && day >= 23 || month == 9 && day <= 22) return "Virgo";
if (month == 9 && day >= 23 || month == 10 && day <= 22) return "Libra";
if (month == 10 && day >= 23 || month == 11 && day <= 21) return "Scorpio";
if (month == 11 && day >= 22 || month == 12 && day <= 21) return "Sagittarius";
return "";
}
// This method calculates the lunar phase for a given date
private static string GetLunarPhase(DateTime date)
{
// Calculate the Julian date
int year = date.Year;
int month = date.Month;
int day = date.Day;
if (month < 3)
{
year--;
month += 12;
}
int a = year / 100;
int b = a / 4;
int c = 2 - a + b;
int e = (int)(365.25 * (year + 4716));
int f = (int)(30.6001 * (month + 1));
double julianDate = c + day + e + f - 1524.5;
java
Copy code
// Calculate the phase angle of the moon
double moonAge = (julianDate - 2451550.1) / 29.530588853;
double phaseAngle = moonAge - Math.Floor(moonAge);
// Return the lunar phase n**e
if (phaseAngle < 0.03125 || phaseAngle >= 0.96875) return "New Moon";
if (phaseAngle < 0.15625) return "Waxing Crescent";
if (phaseAngle <
继续
0.28125) return "First Quarter";
if (phaseAngle < 0.40625) return "Waxing Gibbous";
if (phaseAngle < 0.53125) return "Full Moon";
if (phaseAngle < 0.65625) return "Waning Gibbous";
if (phaseAngle < 0.78125) return "Last Quarter";
return "Waning Crescent";
}
csharp
Copy code
// This method calculates the auspiciousness for a given date
private static string GetAuspiciousness(DateTime date)
{
// Calculate the components of the date
int year = date.Year;
int month = date.Month;
int day = date.Day;
// Calculate the auspiciousness of the year
int yIndex = (year - 4) % 60;
string[] yAuspiciousness = new string[] { "吉", "凶", "凶", "凶", "凶", "吉", "吉", "凶", "凶", "吉", "吉", "凶", "凶", "凶", "吉", "吉", "凶", "吉", "吉", "吉", "吉", "凶", "凶", "吉", "吉", "凶", "凶", "凶", "凶", "吉", "凶", "凶", "吉", "吉", "凶", "吉", "吉", "吉", "吉", "凶", "凶", "吉", "凶", "凶", "吉", "吉", "凶", "凶", "凶", "吉", "吉", "凶", "吉", "吉", "吉", "吉", "凶", "凶", "吉", "凶", "凶", "凶" };
string yAuspicious = yAuspiciousness[yIndex];
// Calculate the auspiciousness of the month
int mIndex = (month - 1) % 12;
string[] mAuspiciousness = new string[] { "凶", "凶", "凶", "凶", "吉", "吉", "吉", "吉", "凶", "凶", "凶", "凶" };
string mAuspicious = mAuspiciousness[mIndex];
// Calculate the auspiciousness of the day
int dIndex = (day - 1) % 30;
string[] dAuspiciousness = new string[] { "吉", "吉", "吉", "吉", "吉", "凶", "凶", "凶", "凶", "凶", "吉", "吉", "吉", "吉", "吉", "凶", "凶", "凶", "凶", "吉", "吉", "吉", "吉", "吉", "凶", "凶", "凶", "吉", "吉", "吉" };
string dAuspicious = dAuspiciousness[dIndex];
// Return the combined auspiciousness
if (yAuspicious == "吉" && mAuspicious == "吉" && dAuspicious == "
继续
吉")
{
return "吉";
}
else
{
return "凶";
}
}
}
// This is the **in form class for the calendar application
public partial class CalendarForm : Form
{
private const int minYear = 1;
private const int **xYear = 9999;
scss
Copy code
private DateTime currentDate;
private DateTime selectedDate;
// This method initializes the form
public CalendarForm()
{
InitializeComponent();
// Set the initial date and update the display
currentDate = DateTime.Today;
selectedDate = currentDate;
UpdateDisplay();
}
// This method updates the display of the form
private void UpdateDisplay()
{
// Update the month and year labels
monthLabel.Text = selectedDate.ToString("MMMM");
yearLabel.Text = selectedDate.ToString("yyyy");
// Clear the day labels
for (int i = 0; i < 42; i++)
{
dayLabels[i].Text = "";
dayLabels[i].BackColor = SystemColors.Window;
}
// Calculate the first day of the month
DateTime firstDayOfMonth = new DateTime(selectedDate.Year, selectedDate.Month, 1);
int firstDayOfWeek = (int)firstDayOfMonth.DayOfWeek;
int daysInMonth = DateTime.DaysInMonth(selectedDate.Year, selectedDate.Month);
// Update the day labels
for (int i = 0; i < daysInMonth; i++)
{
int index = firstDayOfWeek + i;
dayLabels[index].Text = (i + 1).ToString();
}
// Highlight the selected day
int selectedDay = selectedDate.Day;
if (selectedDate.Month == currentDate.Month && selectedDate.Year == currentDate.Year)
{
int selectedDayOfWeek = (int)selectedDate.DayOfWeek;
int selectedDayIndex = firstDayOfWeek + selectedDay - 1;
dayLabels[selectedDayIndex].BackColor = SystemColors.Highlight;
}
// Update the infor**tion labels
string dateText = selectedDate.ToString("yyyy年M月d日");
dateLabel.Text = dateText;
string lunarText = LunarCalendar.GetLunarDateString(selectedDate);
lunarLabel.Text = lunarText;
string zodiacText = LunarCalendar.GetZodiac(selectedDate);
zodiacLabel.Text = zodiacText;
string constellationText = Astrology.GetConstellation(selectedDate);
constellationLabel.Text = constellationText;
string phaseText = Astrology.GetMoonPhase(selectedDate);
phaseLabel.Text = phaseText;
string auspiciousnessText = LunarCalendar.GetAuspiciousness(selectedDate);
auspiciousnessLabel.Text = auspiciousnessText;
}
// These methods handle the click events for the previous and next buttons
private void previousButton_Click(object sender, EventArgs e)
{
selectedDate = selectedDate.AddMonths(-1);
UpdateDisplay();
}
private void nextButton_Click(object sender, EventArgs e)
{
selectedDate = selectedDate.AddMonths(1);
UpdateDisplay();
}
// This method handles the click event for a day label
private void dayLabel_Click(object sender, EventArgs e)
{
Label label = (Label)sender;
if (label.Text != "")
{
int day = int.Parse(label.Text);
selectedDate = new DateTime(selectedDate.Year, selectedDate.Month, day);
UpdateDisplay();
}
}
// This method handles the key events for the form
private void CalendarForm_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Left:
selected
继续
Date = selectedDate.AddMonths(-1);
UpdateDisplay();
break;
case Keys.Right:
selectedDate = selectedDate.AddMonths(1);
UpdateDisplay();
break;
case Keys.Up:
selectedDate = selectedDate.AddDays(-7);
UpdateDisplay();
break;
case Keys.Down:
selectedDate = selectedDate.AddDays(7);
UpdateDisplay();
break;
case Keys.Home:
selectedDate = new DateTime(selectedDate.Year, selectedDate.Month, 1);
UpdateDisplay();
break;
case Keys.End:
selectedDate = new DateTime(selectedDate.Year, selectedDate.Month, DateTime.DaysInMonth(selectedDate.Year, selectedDate.Month));
UpdateDisplay();
break;
case Keys.Enter:
currentDate = selectedDate;
UpdateDisplay();
break;
}
}
}
继续
接下来我们需要实现一个方法,用于根据选定的日期更新日历界面的显示。
首先,在CalendarForm类中添加以下私有方法:
private void UpdateDisplay()
{
// 更新标题栏
lblMonthAndYear.Text = selectedDate.ToString("MMMM yyyy", CultureInfo.InvariantCulture);
scss
Copy code
// 获取当前月份的第一天和最后一天
DateTime firstDayOfMonth = new DateTime(selectedDate.Year, selectedDate.Month, 1);
DateTime lastDayOfMonth = new DateTime(selectedDate.Year, selectedDate.Month, DateTime.DaysInMonth(selectedDate.Year, selectedDate.Month));
// 获取上个月份的最后一天
DateTime lastDayOfPrevMonth = firstDayOfMonth.AddDays(-1);
// 获取下个月份的第一天
DateTime firstDayOfNextMonth = lastDayOfMonth.AddDays(1);
// 获取本月的天数
int daysInMonth = DateTime.DaysInMonth(selectedDate.Year, selectedDate.Month);
// 获取本月第一天是星期几
int firstDayOfWeek = (int)firstDayOfMonth.DayOfWeek;
// 获取上个月的天数
int daysInPrevMonth = DateTime.DaysInMonth(lastDayOfPrevMonth.Year, lastDayOfPrevMonth.Month);
// 获取需要显示的行数
int numRows = (int)Math.Ceiling((firstDayOfWeek + daysInMonth) / 7.0);
// 清空日历控件
tableLayoutPanel1.Controls.Clear();
// 添加日历的日期部分
for (int i = 0; i < numRows; i++)
{
for (int j = 0; j < 7; j++)
{
int day = i * 7 + j - firstDayOfWeek + 1;
Label label = new Label();
label.TextAlign = ContentAlignment.MiddleCenter;
label.Margin = new Padding(0);
label.Padding = new Padding(0);
label.AutoSize = false;
label.Size = new Size(tableLayoutPanel1.Width / 7, tableLayoutPanel1.Height / numRows);
label.Font = new Font("Microsoft Sanerif", 9F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0)));
if (i == 0 && j < firstDayOfWeek)
{
// 显示上个月的日期
int prevMonthDay = daysInPrevMonth - firstDayOfWeek + j + 1;
label.Text = prevMonthDay.ToString();
label.ForeColor = Color.Gray;
}
else if (day > daysInMonth)
{
// 显示下个月的日期
int nextMonthDay = day - daysInMonth;
label.Text = nextMonthDay.ToString();
label.ForeColor = Color.Gray;
}
else
{
// 显示本月的日期
label.Text = day.ToString();
label.ForeColor = Color.Black;
// 设置选中日期的样式
if (selectedDate.Year == currentDate.Year && selectedDate.Month == currentDate.Month && day == currentDate.Day)
{
label.BackColor = Color.LightBlue;
}
// 添加鼠标点击事件
label.Click += new EventHandler(label_Click);
}
tableLayoutPanel1.Controls.Add(label, j, i);
}
}
// 添加日历的星期几部分
string[] daysOfWeek = new string[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
for (int i = 0; i < 7; i++)
继续
css
Copy code
{
Label label = new Label();
label.TextAlign = ContentAlignment.MiddleCenter;
label.Margin = new Padding(0);
label.Padding = new Padding(0);
label.AutoSize = false;
label.Size = new Size(tableLayoutPanel1.Width / 7, tableLayoutPanel1.Height / numRows / 2);
label.Font = new Font("Microsoft Sanerif", 9F, FontStyle.Bold, GraphicsUnit.Point, ((byte)(0)));
label.ForeColor = Color.Black;
label.BackColor = Color.Transparent;
label.Text = daysOfWeek[i];
tableLayoutPanel1.Controls.Add(label, i, numRows);
}
}
在该方法中,我们首先获取了当前选定日期所在月份的第一天和最后一天,以及上个月份的最后一天和下个月份的第一天,还有本月的天数和第一天是星期几。然后我们清空了日历控件,并依次添加日历的日期和星期几部分。
对于日期部分的添加,我们首先计算出需要显示的行数,然后使用两层循环依次添加每个日期标签。对于每个标签,我们判断它是不是上个月的日期、下个月的日期还是本月的日期,并相应地设置它的文本、前景色和背景色。如果该标签显示的是本月的日期,并且它的日期等于当前日期,则我们将它的背景色设置为浅蓝色,以表示当前日期。
最后,我们添加了每个星期几的标签,并将它们添加到日历控件中。
现在,我们需要在label_Click方法中调用UpdateDisplay方法,以便在选定日期变化时更新日历的显示。修改label_Click方法如下:
private void label_Click(object sender, EventArgs e)
{
Label label = (Label)sender;
int day = int.Parse(label.Text);
selectedDate = new DateTime(selectedDate.Year, selectedDate.Month, day);
UpdateDisplay();
}
在该方法中,我们首先获取被点击的标签的日期,并将选定日期设置为该日期。然后我们调用UpdateDisplay方法来更新日历的显示。
现在,我们已经完成了日历窗体的设计和实现。最后,我们需要在Form1类中添加一个按钮,用于打开日历窗体。在Form1的设计器中,添加一个按钮控件,设置它的Text属性为"Show Calendar",将它的Dock属性设置为Bot***,然后双击它来生成Click事件处理方法。在该方法中,添加以下代码:
private void btnShowCalendar_Click(object sender, EventArgs e)
{
CalendarForm calendarForm = new CalendarForm();
calendarForm.ShowDialog();
}
在该方法中,我们创建了一个CalendarForm实例,并调用它的ShowDialog方法来显示该窗体。
现在,我们已经完成了整个程序的设计和实现。将上述代码**到Microsoft Visual Studio 2022中,然后编译运行,就可以看到我们设计的日历程序了。 |
|