adressmoeistranici
@adressmoeistranici
Делатель

Какая архитектура должна быть у такой попытки?

Здравствуйте, помогите пожалуйста понять, как должна быть исправлена эта программа, чтоб вызывались события.
Не вызываются потому что делегатов нет?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Threading;
using System.IO;
using System.Windows.Forms;

namespace Wallpaper_Master
{
    static class Program
    {
        const int SPI_SETDESKWALLPAPER = 20;
        const int SPIF_UPDATEINIFILE = 0x01;
        const int SPIF_SENDWININICHANGE = 0x02;
        private static bool secret = false;
        private static string fileStandart = "";
        private static string fileSecret = "";
        /// <summary>
        /// Главная точка входа для приложения.
        /// </summary>
        [STAThread]
        static void Main()
        {
            if (Connect.RegistryCheck())
            {
                CheckFiles();
                if (fileStandart != "")
                {
                    SetWallpaper(fileStandart, 2, 0);
                    secret = false;
                }
                else
                {
                    fileStandart = "C:/Windows/Web/Wallpaper/Landscapes/img11.jpg";
                    SetWallpaper(fileStandart, 2, 0);
                    secret = false;
                }
                SystemEvents.PowerModeChanged += new PowerModeChangedEventHandler(OnPowerModeChanged);
                Application.ApplicationExit += new EventHandler(OnApplicationExit);
                if (fileSecret != "")
                {
                    //поток c отловом комбинации клавиш

                    //join
                }
            }
        }
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);
        public static void SetWallpaper(string path, int style, int tile)
        {
            RegistryKey rk = Registry.CurrentUser.CreateSubKey("Control Panel\\Desktop");
            rk.SetValue("WallpaperStyle", style.ToString());
            rk.SetValue("TileWallpaper", tile.ToString());
            SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, path, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
        }
        private static void CheckFiles()
        {
            string pathStandart = Application.StartupPath.ToString() + "\\Standart";
            string pathSecret = Application.StartupPath.ToString() + "\\Secret";
            if (!Directory.Exists(pathStandart))
            {
                Directory.CreateDirectory(pathStandart);
            }
            else
            {
                string[] jpg = Directory.GetFiles(pathStandart);
                fileStandart = "";
                foreach (string s in jpg)
                {
                    if (s.Contains(".jpg"))
                    {
                        fileStandart = s;
                    }
                }
            }
            if (!Directory.Exists(pathSecret))
            {
                Directory.CreateDirectory(pathSecret);
            }
            else
            {
                string[] jpg = Directory.GetFiles(pathSecret);
                fileSecret = "";
                foreach (string s in jpg)
                {
                    if (s.Contains(".jpg"))
                    {
                        fileSecret = s;
                    }
                }
            }
        }
        private static void OnPowerModeChanged(object sender, PowerModeChangedEventArgs e)
        {
            if (e.Mode == PowerModes.Suspend)
            {
                if (fileStandart != "")
                {
                    SetWallpaper(fileStandart, 2, 0);
                    secret = false;
                }
                else
                {
                    fileStandart = "C:/Windows/Web/Wallpaper/Landscapes/img11.jpg";
                    SetWallpaper(fileStandart, 2, 0);
                    secret = false;
                }
                SystemEvents.PowerModeChanged -= new PowerModeChangedEventHandler(OnPowerModeChanged);
                Application.ApplicationExit -= new EventHandler(OnApplicationExit);
                Connect.RegistryClean();
            }
            else if (e.Mode == PowerModes.Resume)
            {
                SystemEvents.PowerModeChanged += new PowerModeChangedEventHandler(OnPowerModeChanged);
                Application.ApplicationExit += new EventHandler(OnApplicationExit);
                CheckFiles();
            }
            Console.WriteLine("power mode");
        }
        private static void OnApplicationExit(object sender, EventArgs e)
        {
            CheckFiles();
            if (fileStandart != "")
            {
                SetWallpaper(fileStandart, 2, 0);
                secret = false;
            }
            else
            {
                fileStandart = "C:/Windows/Web/Wallpaper/Landscapes/img11.jpg";
                SetWallpaper(fileStandart, 2, 0);
                secret = false;
            }
            SystemEvents.PowerModeChanged -= new PowerModeChangedEventHandler(OnPowerModeChanged);
            Application.ApplicationExit -= new EventHandler(OnApplicationExit);
            Connect.RegistryClean();
            Console.WriteLine("application exit");
        }
    }
}
  • Вопрос задан
  • 189 просмотров
Решения вопроса 1
@cicatrix
было бы большой ошибкой думать
Читайте документацию

This event is only raised if the message pump is running. In a Windows service, unless a hidden form is used or the message pump has been started manually, this event will not be raised. For a code example that shows how to handle system events by using a hidden form in a Windows service, see the SystemEvents class.


Событие генерируется только если работает конвейер сообщений. По вашему коду этого не наблюдается.
Вот здесь второй пример показывает, как перехватывать системные события из службы.
Если вы не хотите делать службу, думаю, проще будет всё-таки запустить message pump через Application.Run.
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы