Windows service + wallpaper

07/12/2010

0

Olá pessoal preciso de uma ajudinha aqui.
E o seguinte estou criando um sisteminha qua altera o papel de parede do desktop, de tempos em tempos determinado por um setor especifico aqui na empresa.

Então tenho um windows service que verifica esta alteração e seria para ele efetuar essa troca o que não está acontecendo,

quando utilizo os mesmos métodos de troca de papel de parede via execitavel ele funciona legal, mais quando coloco
como um serviço nada acontece ele somente passa por todo o código onde coloquei log's para ver se havia erro ou não e não há erros.

Então se alguém poder me ajudar envio o cógo;

 public class Wallpaper
    {

         const UInt32 SPI_SETDESKWALLPAPER = 20;      
        const int SPIF_UPDATEINIFILE = 0x01;
        const int SPIF_SENDWININICHANGE = 0x02;      

        [DllImport("user32.dll", CharSet = CharSet.Auto,SetLastError=true)]   
        public static extern Int32 SystemParametersInfo(UInt32 uiAction, UInt32 uiParam, String pvParam, UInt32 fWinIni);
     

        public Wallpaper() //Classe que efetua a troca do papel de parede
        {
            //
            // TODO: Add constructor logic here
            //
        }


        public enum Style : int //Cria o Enum contendo os estilos
        {
            Tiled, Centered, Stretched
        }

        public void SetWallpaper(string path, Style style)
        {

            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop\", true);


            switch (style)
            {
                case Style.Stretched:
                    key.SetValue(@"WallpaperStyle", "2");
                    key.SetValue(@"TileWallpaper", "0");
                    break;
                case Style.Centered:
                    key.SetValue(@"WallpaperStyle", "1");
                    key.SetValue(@"TileWallpaper", "0");
                    break;
                case Style.Tiled:
                    key.SetValue(@"WallpaperStyle", "1");
                    key.SetValue(@"TileWallpaper", "1");
                    break;
            }

            Wallpaper.SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, path, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);     
            key = null;
        }

           
    }

Bom como disse antes esta classe funciona beleza, mais como serviço não altera o papel de parede.
  

Wallpaper w = new Wallpaper();
w.SetWallpaper("Caminho da imagem", (Wallpaper.Style)2);

Agradeço a todos que contribuirem
Joaquim Simão

Joaquim Simão

Responder

Posts

09/12/2010

Netasper

Cria um arquivo batch!
Responder

09/12/2010

Joaquim Simão

Obrigado por sua ajuda, mais consegui resolver criando esta classe.


using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.IO;

namespace InteractiveProcessFromService
{
    class InteractiveProcessRunner
    {
        private string m_ApplicationPath;
        private IntPtr m_SessionTokenHandle;
              
        public string CommandLine { get; set; }
        public string WorkingDirectory { get; set; }
        public bool CreateNoWindow { get; set; }
        public string Desktop { get; set; }

        private const int NORMAL_PRIORITY_CLASS = 0x20;
        private const int CREATE_UNICODE_ENVIRONMENT = 0x400;
        private const int CREATE_NO_WINDOW = 0x08000000;

        public InteractiveProcessRunner(string appPath, IntPtr hSessionToken)
        {
            m_ApplicationPath = appPath;
            m_SessionTokenHandle = hSessionToken;
           
         
            WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.System);

            Desktop = "WinSta0\\Default";
        }
       
        public int Run()
        {
            STARTUPINFO si = new STARTUPINFO();
            si.lpDesktop = Desktop;
            PROCESSINFO pi = new PROCESSINFO();

            int creationFlags = NORMAL_PRIORITY_CLASS | CREATE_UNICODE_ENVIRONMENT;
            creationFlags |= CreateNoWindow ? CREATE_NO_WINDOW : 0;

            IntPtr envBlock;
            if (!CreateEnvironmentBlock(out envBlock, m_SessionTokenHandle, 0))
            {
                throw new System.ComponentModel.Win32Exception();
            }

            try
            {
                if (!CreateProcessAsUser(m_SessionTokenHandle, m_ApplicationPath, CommandLine, IntPtr.Zero,
                    IntPtr.Zero, 0, creationFlags, envBlock, WorkingDirectory,
                    si, pi))
                {
                    throw new System.ComponentModel.Win32Exception();
                }
            }
            finally
            {
                DestroyEnvironmentBlock(envBlock);
            }

            CloseHandle(pi.hThread);
            CloseHandle(pi.hProcess);

            return pi.dwProcessId;
        }

        [DllImport("AdvApi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool CreateProcessAsUser(IntPtr hToken, string lpApplicationName,
            string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes,
            int bInheritHandles, int dwCreationFlags, IntPtr lpEnvironment,
            string lpCurrentDirectory, STARTUPINFO lpStartupInfo,
            [Out]PROCESSINFO lpProcessInformation);


        [DllImport("kernel32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool CloseHandle(IntPtr hObj);

        [DllImport("userenv.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool CreateEnvironmentBlock(out IntPtr lpEnvironment,
            IntPtr hToken, int bInherit);

        [DllImport("userenv.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool DestroyEnvironmentBlock(IntPtr lpEnvironment);

    }
}


e no lugar de chamr um Process.start("caminho");

chamo:

 InteractiveProcessRunner runner =
                        new InteractiveProcessRunner(@"C:\Program Files\Hospital anchieta\Troca papel de parede\MudaTelaDesktop.exe", hSessionToken);
                   
                    runner.Run();


Responder

Que tal ter acesso a um e-book gratuito que vai te ajudar muito nesse momento decisivo?

Ver ebook

Recomendado pra quem ainda não iniciou o estudos.

Eu quero
Ver ebook

Recomendado para quem está passando por dificuldades nessa etapa inicial

Eu quero

Utilizamos cookies para fornecer uma melhor experiência para nossos usuários, consulte nossa política de privacidade.

Aceitar