事实证明,Win32 (c++) 代码可以快速更改桌面背景(在 i5 3.2ghz 上不到 20 毫秒),而托管 C# 代码需要 500 到 3000 毫秒。但是,非托管 c++ 代码需要永远绘制图像(300 到 1500 毫秒)。所以我所做的就是制作两个可以协同工作的程序。托管 C# 程序创建图像(在 20 毫秒内)然后保存。非托管 c++ 将保存的图像设置为桌面背景。
C# static void Main(string[] args) { //手动计算和硬编码的图像位置 //第一个图像位置 //X:532 //Y:335 位图 TheImage = new Bitmap(1366, 768);
Graphics G = Graphics.FromImage(TheImage);
DateTime DTNow = DateTime.Now;
while (true)
{
//get the time
DTNow = DateTime.Now;
//draw the canvas
G.DrawImage(Resources.canvas, 0, 0,1366,768);
//draw the first image of the hour
G.DrawImage(GetImage(DTNow.Hour,0),532,330,174,217);
//draw the second image of the hour
G.DrawImage(GetImage(DTNow.Hour, 1), 711, 330, 174, 217);
//draw the colon
if (DTNow.Second % 2 == 0) G.DrawImage(Resources.aColon, 890, 365,57,147);
//draw the first digit of the minute
G.DrawImage(GetImage(DTNow.Minute, 0), 952, 330, 174, 217);
//draw the second digit of the minute
G.DrawImage(GetImage(DTNow.Minute, 1), 1131, 330, 174, 217);
//save the file
try
{
File.Delete("C:\\background.bmp");
TheImage.Save("C:\\background.bmp", ImageFormat.Bmp);
}
catch
{
}
//calculate sleep time and sleep until next second
DTNow = DateTime.Now.AddSeconds(1);
DateTime NextSecond = new DateTime(DTNow.Year,DTNow.Month,DTNow.Day, DTNow.Hour,DTNow.Minute, DTNow.Second,500);
DTNow = DateTime.Now;
System.Threading.Thread.Sleep((int)NextSecond.Subtract(DTNow).TotalMilliseconds);
}
}
static Bitmap GetImage(int Number, int Index)
{
string NS = Number.ToString();
if (NS.Length < 2) NS = "0" + NS;
char[] digits = NS.ToCharArray();
switch (digits[Index])
{
case '1': { return Resources.a1; }
case '2': { return Resources.a2; }
case '3': { return Resources.a3; }
case '4': { return Resources.a4; }
case '5': { return Resources.a5; }
case '6': { return Resources.a6;}
case '7': { return Resources.a7;}
case '8': { return Resources.a8;}
case '9': { return Resources.a9; }
default: { return Resources.a0; }
}
}
}
c++ int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, char*, int nShowCmd) { while(true){ SystemParametersInfo(SPI_SETDESKWALLPAPER,0, L"C:\background.bmp", SPIF_UPDATEINIFILE); int MS = (int)(((long)floor((long)clock()/(long)CLOCKS_PER_SEC)*1000l+1000l)-((long)clock()));
if(MS<=1000 && MS>0){
std::this_thread::sleep_for(std::chrono::milliseconds(MS));
}
else
{
}
}
return 0;
}