AdvancedBackgroundJimmy.Program.cs

using AdvancedBackground;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.ServiceProcess;
using System.Threading.Tasks;
using System.Timers; namespace AdvancedBackgroundJimmy
{
[System.Runtime.Remoting.Contexts.Synchronization]
static class Program
{ const int SPI_GETDESKWALLPAPER = 0x73;
const int MAX_PATH = ;
const int SPI_SETDESKWALLPAPER = 0x14;
const int SPIF_UPDATEINIFILE = 0x01;
const int SPIF_SENDININICHANGE = 0x02;
static string photoFileDirPath = @"g:/Photos/Camera/";
static DirectoryInfo photoDir = new DirectoryInfo(photoFileDirPath);
static FileInfo[] photoFileArr = photoDir.GetFiles();
static int PHOTO_PER_WAIT = ;
static string log_path = @"g:/TestLog/AdvancedBackgroundJimmy/log.txt";
static FileInfo logFileInfo = new FileInfo(log_path);
static string log = null; /// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
//ServiceBase[] servicesToRun = new ServiceBase[]
//{
// new AdvancedBackgroundServiceJimmy()
//};
//ServiceBase.Run(servicesToRun);
AutoPhoto();
} public static void AutoPhoto()
{
try
{
log = "进入AutoPhoto方法!" + System.Environment.NewLine;
File.AppendAllText(log_path, log);
FileInfo[] fileArr = photoFileArr;
for (int i = ; i < fileArr.Length; i++)
{
FileInfo photoFile = fileArr[i];
log = "当前图片路径:" + photoFile.FullName + System.Environment.NewLine;
File.AppendAllText(log_path, log);
SetWallpaper2(photoFile.FullName, WallpaperStyle.Centered);
//SHChangeNotify(HChangeNotifyEventID.SHCNE_ASSOCCHANGED, HChangeNotifyFlags.SHCNF_IDLIST, IntPtr.Zero, IntPtr.Zero);
if (i == fileArr.Length - )
{
i = -;
}
System.Threading.Thread.Sleep(PHOTO_PER_WAIT);
}
}
catch(Exception e)
{
log = e.Message + System.Environment.NewLine;
File.AppendAllText(log_path, log);
}
} const int WM_SETTINGCHANGE = 0x001A;
const int HWND_BROADCAST = 0xffff; static IntPtr result1; public enum SendMessageTimeoutFlags : uint
{
SMTO_NORMAL = 0x0000,
SMTO_BLOCK = 0x0001,
SMTO_ABORTIFHUNG = 0x0002,
SMTO_NOTIMEOUTIFNOTHUNG = 0x0008
} [DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni); [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
static extern int GetLastError(); public enum WallpaperStyle : int
{
Tiled,
Centered,
Stretched,
Fill,
Fit
} /// <summary>
/// 返回当前的系统壁纸路径
/// </summary>
/// <returns></returns>
public static string GetDesktopWallpaper()
{
string wallpaper = new string('\0', MAX_PATH);
try
{
int ret = SystemParametersInfo(SPI_GETDESKWALLPAPER, (int)wallpaper.Length, wallpaper, );
}
catch (Exception e)
{
log = e.Message + System.Environment.NewLine;
File.AppendAllText(log_path, log);
}
return wallpaper.Substring(, wallpaper.IndexOf('\0'));
} [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern IntPtr SendMessageTimeout(
IntPtr windowHandle,
uint Msg,
IntPtr wParam,
IntPtr lParam,
SendMessageTimeoutFlags flags,
uint timeout,
out IntPtr result
); /// 桌面刷新
/// </summary>
[DllImport("shell32.dll")]
public static extern void SHChangeNotify(HChangeNotifyEventID wEventId, HChangeNotifyFlags uFlags, IntPtr dwItem1, IntPtr dwItem2); public static void DeskRef()
{
SHChangeNotify(HChangeNotifyEventID.SHCNE_ASSOCCHANGED, HChangeNotifyFlags.SHCNF_IDLIST, IntPtr.Zero, IntPtr.Zero);
} #region
[Flags]
public enum HChangeNotifyFlags
{
SHCNF_DWORD = 0x0003,
SHCNF_IDLIST = 0x0000,
SHCNF_PATHA = 0x0001,
SHCNF_PATHW = 0x0005,
SHCNF_PRINTERA = 0x0002,
SHCNF_PRINTERW = 0x0006,
SHCNF_FLUSH = 0x1000,
SHCNF_FLUSHNOWAIT = 0x2000
}
#endregion #region enum HChangeNotifyEventID
[Flags]
public enum HChangeNotifyEventID
{
SHCNE_ALLEVENTS = 0x7FFFFFFF,
SHCNE_ASSOCCHANGED = 0x08000000,
SHCNE_ATTRIBUTES = 0x00000800,
SHCNE_CREATE = 0x00000002,
SHCNE_DELETE = 0x00000004,
SHCNE_DRIVEADD = 0x00000100,
SHCNE_DRIVEADDGUI = 0x00010000,
SHCNE_DRIVEREMOVED = 0x00000080,
SHCNE_EXTENDED_EVENT = 0x04000000,
SHCNE_FREESPACE = 0x00040000,
SHCNE_MEDIAINSERTED = 0x00000020,
SHCNE_MEDIAREMOVED = 0x00000040,
SHCNE_MKDIR = 0x00000008,
SHCNE_NETSHARE = 0x00000200,
SHCNE_NETUNSHARE = 0x00000400,
SHCNE_RENAMEFOLDER = 0x00020000,
SHCNE_RENAMEITEM = 0x00000001,
SHCNE_RMDIR = 0x00000010,
SHCNE_SERVERDISCONNECT = 0x00004000,
SHCNE_UPDATEDIR = 0x00001000,
SHCNE_UPDATEIMAGE = 0x00008000,
}
#endregion [DllImport("user32.dll")]
public static extern bool InvalidateRect(IntPtr hwnd, IntPtr lpRect, bool bErase); public static void SetWallpaper2(string path, WallpaperStyle style)
{
try
{
log = "进入SetWallpaper方法!" + System.Environment.NewLine;
File.AppendAllText(log_path, log);
log = "时间:" + DateTime.Now.ToString() + System.Environment.NewLine;
File.AppendAllText(log_path, log);
//System.Drawing.Image img = System.Drawing.Image.FromStream(s);
//string tempPath = Path.Combine(Path.GetTempPath(), "wallpaper.bmp");
//img.Save(tempPath, System.Drawing.Imaging.ImageFormat.Bmp);
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true);
key.SetValue(@"Wallpaper", path);
if (style == WallpaperStyle.Stretched)
{
key.SetValue(@"WallpaperStyle", .ToString());
key.SetValue(@"TileWallpaper", .ToString());
}
else if (style == WallpaperStyle.Centered)
{
key.SetValue(@"WallpaperStyle", .ToString());
key.SetValue(@"TileWallpaper", .ToString());
}
else if (style == WallpaperStyle.Tiled)
{
key.SetValue(@"WallpaperStyle", .ToString());
key.SetValue(@"TileWallpaper", .ToString());
}
else if (style == WallpaperStyle.Fit) //Win 7 or later
{
key.SetValue(@"WallpaperStyle", .ToString());
key.SetValue(@"TileWallpaper", .ToString());
}
else if (style == WallpaperStyle.Fill) //Win 7 or later
{
key.SetValue(@"WallpaperStyle", .ToString());
key.SetValue(@"TileWallpaper", .ToString());
}
else
{ }
int ret = SystemParametersInfo(SPI_SETDESKWALLPAPER, , path, SPIF_UPDATEINIFILE | SPIF_SENDININICHANGE);
if (ret > )
{
log = "结果:" + ret + System.Environment.NewLine;
File.AppendAllText(log_path, log);
}
else
{
int errCode = GetLastError();
log = "错误码:" + errCode + System.Environment.NewLine;
File.AppendAllText(log_path, log);
}
key.Flush();
key.Close();
//通知所有打开的程序注册表以修改
//SendMessageTimeout(new IntPtr(HWND_BROADCAST), WM_SETTINGCHANGE, IntPtr.Zero, IntPtr.Zero, SendMessageTimeoutFlags.SMTO_NORMAL, 1000, out result1);
//DeskRef();
//InvalidateRect(IntPtr.Zero, IntPtr.Zero, true);
}
catch (Exception e)
{
log = e.Message + System.Environment.NewLine;
File.AppendAllText(log_path, log);
}
} }
}

ProjectInstaller.cs

using Microsoft.Win32;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.Management; namespace AdvancedBackgroundJimmy
{
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{ public ProjectInstaller()
{
InitializeComponent();
} protected override void OnCommitted(System.Collections.IDictionary savedState)
{
base.OnCommitted(savedState);
//将服务更改为允许桌面交互模式
ConnectionOptions coOptions = new ConnectionOptions();
coOptions.Impersonation = ImpersonationLevel.Impersonate;
ManagementScope mgmtScope = new System.Management.ManagementScope(@"root\CIMV2", coOptions);
mgmtScope.Connect();
ManagementObject wmiService;
wmiService = new ManagementObject("Win32_Service.Name='" + this.serviceInstaller1.ServiceName + "'");
ManagementBaseObject InParam = wmiService.GetMethodParameters("Change");
InParam["DesktopInteract"] = true;
ManagementBaseObject OutParam = wmiService.InvokeMethod("Change", InParam, null);
} }
}

AdvancedBackgroundServiceJimmy.cs

using AdvancedBackground;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Windows.Forms; namespace AdvancedBackgroundJimmy
{
partial class AdvancedBackgroundServiceJimmy : ServiceBase
{ static String log_path = @"g:/TestLog/AdvancedBackgroundJimmy/log.txt";
static FileInfo logFileInfo = new FileInfo(log_path);
static String log = null;
static Thread thread = null; [DllImport("user32.dll")]
static extern int GetDesktopWindow(); [DllImport("user32.dll")]
static extern IntPtr GetProcessWindowStation(); [DllImport("kernel32.dll")]
static extern IntPtr GetCurrentThreadId(); [DllImport("user32.dll")]
static extern IntPtr GetThreadDesktop(IntPtr dwThread); [DllImport("user32.dll")]
static extern IntPtr OpenWindowStation(string a, bool b, int c); [DllImport("user32.dll")]
static extern IntPtr OpenDesktop(string lpszDesktop, uint dwFlags,
bool fInherit, uint dwDesiredAccess); [DllImport("user32.dll")]
static extern IntPtr CloseDesktop(IntPtr p); [DllImport("rpcrt4.dll", SetLastError = true)]
static extern IntPtr RpcImpersonateClient(int i); [DllImport("rpcrt4.dll", SetLastError = true)]
static extern IntPtr RpcRevertToSelf(); [DllImport("user32.dll")]
static extern IntPtr SetThreadDesktop(IntPtr a); [DllImport("user32.dll")]
static extern IntPtr SetProcessWindowStation(IntPtr a); [DllImport("user32.dll")]
static extern IntPtr CloseWindowStation(IntPtr a); public AdvancedBackgroundServiceJimmy()
{
InitializeComponent();
if (!logFileInfo.Exists)
{
logFileInfo.CreateText();
}
} protected override void OnStart(string[] args)
{
if (!logFileInfo.Exists)
{
logFileInfo.CreateText();
}
log = "进入OnStart方法!" + System.Environment.NewLine;
File.AppendAllText(log_path, log);
ThreadStart threadStart = new ThreadStart(delegate()
{
try
{
if (!logFileInfo.Exists)
{
logFileInfo.CreateText();
}
GetDesktopWindow();
IntPtr hwinstaSave = GetProcessWindowStation();
IntPtr dwThreadId = GetCurrentThreadId();
IntPtr hdeskSave = GetThreadDesktop(dwThreadId);
IntPtr hwinstaUser = OpenWindowStation("WinSta0", false, );
if (hwinstaUser == IntPtr.Zero)
{
RpcRevertToSelf();
return;
}
SetProcessWindowStation(hwinstaUser);
IntPtr hdeskUser = OpenDesktop("Default", , false, );
RpcRevertToSelf();
if (hdeskUser == IntPtr.Zero)
{
SetProcessWindowStation(hwinstaSave);
CloseWindowStation(hwinstaUser);
return;
}
SetThreadDesktop(hdeskUser);
IntPtr dwGuiThreadId = dwThreadId;
AdvancedBackgroundJimmy.Program.AutoPhoto();
dwGuiThreadId = IntPtr.Zero;
SetThreadDesktop(hdeskSave);
SetProcessWindowStation(hwinstaSave);
CloseDesktop(hdeskUser);
CloseWindowStation(hwinstaUser);
}
catch (Exception e)
{
log = e.Message + System.Environment.NewLine;
File.AppendAllText(log_path, log);
}
});
thread = new Thread(threadStart);
thread.IsBackground = true;
thread.Start();
//AdvancedBackgroundJimmy.Program.AutoPhoto();
} protected override void OnStop()
{
if(thread != null)
{
if (thread.IsAlive)
{
thread.Abort();
thread = null;
}
}
}
}
}

完成.

修改by:ラピスラズリ(Dawn)

修改日期:2019-10-18 9:22:46

问题:去掉了不小心加上的无用代码

.NET(C#)实现桌面背景切换(控制台应用程序,windows服务版的未实现成功)的更多相关文章

  1. 基于UDP协议的控制台聊天程序(c++版)

    本博客由Rcchio原创,转载请告知作者 ------------------------------------------------------------------------------- ...

  2. C#代码安装Windows服务(控制台应用集成Windows服务)

    最近在为一款C/S架构的科研软件开发云计算版,需要用到WCF,考虑到不需要什么界面以及稳定性,无人值守性,准备用Windows Service作为宿主,无奈Windows Service的安装太为繁复 ...

  3. 微软 WCF的几种寄宿方式,寄宿IIS、寄宿winform、寄宿控制台、寄宿Windows服务

    WCF寄宿方式是一种非常灵活的操作,可以在IIS服务.Windows服务.Winform程序.控制台程序中进行寄宿,从而实现WCF服务的运行,为调用者方便.高效提供服务调用.本文分别对这几种方式进行详 ...

  4. Python3实现Win10桌面背景自动切换

    [本文出自天外归云的博客园] 得空写了个自动切换桌面背景图片的小程序.再不写python就要扔键盘了,对vue还有那么一点好感,天天php真是有够烦. 准备工作 准备个文件夹放在桌面上,平时看到什么高 ...

  5. 第十三篇 一个安装、管理windows服务的桌面程序

    在网上看到一个修改程序入口的程序去把windows 服务修改成控制台的程序,然后利用控制台的程序把服务安装和管理,也想起自己原来也写了一个对windows 报务管理的程序,不过是winform的.   ...

  6. 利用css3新增选择器制作背景切换

    之前写css3的时间都是捡项目需要的来用,没有系统的学习过,这几天好好的补了一下css3的知识,真的获益匪浅!觉得新增的那些选择器是有用至极的!今天就来所这几天的所学做一个点击标签切换背景的效果,是纯 ...

  7. 分享一个自己写的基于JQuery的一个Web背景切换的Demo

    这个效果主要有两个特点: 1. 背景切换的渐变 2. 背景大小自适应 3. 背景自适应保持比例同时, 相对居中 js源码: (function ($) { $.fn.bgChange = functi ...

  8. 找回误删除的UBUNTU16.04桌面壁纸图片,或把桌面背景图片另存。20170114

    今天遇到一个小问题,之前下载并设置为桌面壁纸的一张图片在整理文件的时候不小心删除了.由于想不起来当时从哪里找到的图,所以就想把当前桌面壁纸重新保存.经网上查询,未见正确的保存方法,故写在此处备忘. 1 ...

  9. 如何找出当前活动桌面背景图像的位置/路径(Ubuntu 18.04,GNOME)?

    启动终端并运行以下命令 $ gsettings get org.gnome.desktop.background picture-uri 显示当前设置为桌面背景图片的完整路径.  

随机推荐

  1. 【jQuery学习日记】jQuery实现滚动动画

    需要实现的效果 样式分析: 2个主要部分,头部的标题和导航部分,和主要的功能实现区域: 1.头部 <div id="header"> <h1>动漫视频< ...

  2. Python 【基础常识概念】

    深浅拷贝 浅copy与deepcopy 浅copy: 不管多么复杂的数据结构,浅拷贝都只会copy一层 deepcopy : 深拷贝会完全复制原变量相关的所有数据,在内存中生成一套完全一样的内容,我们 ...

  3. ApplicationContextInitializer的理解和使用

    一.ApplicationContextInitializer 介绍 1.1 作用 ApplicationContextInitializer 接口用于在 Spring 容器刷新之前执行的一个回调函数 ...

  4. drf(请求封装/认证/权限/节流)

    1.请求的封装 class HttpRequest(object): def __init__(self): pass @propery def GET(self): pass @propery de ...

  5. SQL逗号合并一列多行的值

    select stuff((select ','+行名 from 表名 for xml path('')),1,1,'')

  6. iframe 框架父页面刷新子页面

    1.父页面添加: <script> function testBtn(){   var reshSrc = document.getElementById('myFrame').src; ...

  7. MQTT抓包分析

    1. 概述 MQTT(Message Queuing Telemetry Transport,消息队列遥测传输协议),是一种基于发布/订阅(Publish/Subscribe)模式的轻量级通讯协议,该 ...

  8. JavaScript初学者

    学习如逆水行舟,不进则退.要逆流而上,逆战! 学习JavaScript这门语言,作为一个初学者,最重要的就是扎实的基础. 只要有了扎实的功底,在后期的学习中才能来去自如的应对各种逻辑难题 下面我们就来 ...

  9. springboot集成axis1.4

    1.首先通过axis工具根据wsdl文件生成java代码和wsdd文件 set Axis_Lib=/Users/apple/configuration/axis-1_4/lib //lib文件目录se ...

  10. MacOS下的渗透测试工具

    信息收集工具 工具名称 安装命令 CeWL brew install sidaf/pentest/cewl dirb brew install sidaf/pentest/dirb dnsrecon ...