Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)

C# - 환경 변수의 변화를 알리는 WM_SETTINGCHANGE Win32 메시지 사용법

WM_SETTINGCHANGE 메시지는,

WM_SETTINGCHANGE message
; https://learn.microsoft.com/en-us/windows/win32/winmsg/wm-settingchange

시스템의 환경 설정이 바뀌었을 때 발생하는 메시지입니다. 이 메시지를 닷넷에서, 가령 Windows Forms에서는 일반 윈도우 메시지와 같은 방식으로 다루면 되기 때문에 다음과 같이 받아 처리할 수 있습니다.

using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        const uint WM_SETTINGCHANGE = 0x001a;

        public Form1()
        {
            InitializeComponent();
        }

        protected override unsafe void WndProc(ref Message m)
        {
            if (m.Msg == WM_SETTINGCHANGE && m.LParam != IntPtr.Zero)
            {
                char* ptr = (char*)m.LParam.ToPointer();
                string text = new string(ptr);
                MessageBox.Show("WM_SETTINGCHANGE: " + text);
            }

            base.WndProc(ref m);
        }
    }
}

물론, 원한다면 우리도 WM_SETTINGCHANGE 이벤트를 발생시킬 수 있습니다. 가령, 시스템 전역 환경 변수를 레지스트리에 설정한 후 현재 실행 중인 프로세스들 중에 (예를 들어 위에서 구현했던 WinForm 예제처럼) 그 변화에 대해 관심이 있는 프로세스에 알리고 싶다면 WM_SETTINGCHANGE 메시지를 발생시킬 수 있습니다.

"WM_SETTINGCHANGE message" 문서에 그 방법이 간단하게 소개돼 있는데요,

To effect a change in the environment variables for the system or the user, broadcast this message with lParam set to the string "Environment".


이와 관련한 예제 코드는 stackoverflow에도 나와 있습니다.

Setting global environment variables programmatically
; https://stackoverflow.com/questions/48928002/setting-global-environment-variables-programmatically

이것을 C#으로 옮기면 다음과 같이 코딩할 수 있습니다.

using System;
using System.Runtime.InteropServices;

namespace ConsoleApp1
{
    [Flags]
    enum SendMessageTimeoutFlags : uint
    {
        SMTO_NORMAL = 0x0,
        SMTO_BLOCK = 0x1,
        SMTO_ABORTIFHUNG = 0x2,
        SMTO_NOTIMEOUTIFNOTHUNG = 0x8,
        SMTO_ERRORONEXIT = 0x20
    }

    internal class Program
    {
        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern IntPtr SendMessageTimeout(
            IntPtr hWnd, uint Msg, UIntPtr wParam, IntPtr lParam,
            SendMessageTimeoutFlags fuFlags, uint uTimeout, out UIntPtr lpdwResult);

        const uint WM_SETTINGCHANGE = 0x001a;

        static void Main(string[] args)
        {
            UIntPtr result = new UIntPtr();

            IntPtr hwndBroadcast = new IntPtr(0xffff);

            SendMessageTimeout(hwndBroadcast, WM_SETTINGCHANGE, UIntPtr.Zero, IntPtr.Zero,
                SendMessageTimeoutFlags.SMTO_NORMAL, 1000, out result);
        }
    }
}

따라서, 처음 소개한 WinForm 예제를 실행 후 위의 SendMessageTimeout 코드를 실행하면 WinForm 예제에서 WM_SETTINGCHANGE 메시지에 대해 반응하는 것을 확인할 수 있습니다.

(첨부 파일은 이 글의 예제 프로젝트를 포함합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 4/5/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  22  23  [24]  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13035정성태4/22/20227673Windows: 204. Windows 10부터 바뀐 QueryPerformanceFrequency, QueryPerformanceCounter
13034정성태4/21/20227024.NET Framework: 1996. C# XingAPI - 주식 종목에 따른 PBR, PER, ROE, ROA 구하는 방법(t3320, t8430 예제)파일 다운로드1
13033정성태4/18/20227622.NET Framework: 1195. C# - Thread.Yield와 Thread.Sleep(0)의 차이점(?)
13032정성태4/17/20227350오류 유형: 805. Github의 50MB 파일 크기 제한 - warning: GH001: Large files detected. You may want to try Git Large File Storage
13031정성태4/15/20226888.NET Framework: 1194. C# - IdealProcessor와 ProcessorAffinity의 차이점
13030정성태4/15/20226540오류 유형: 804. 정규 표현식 오류 - Quantifier {x,y} following nothing.
13029정성태4/14/20226965Windows: 203. iisreset 후에도 이전에 설정한 전역 환경 변수가 w3wp.exe에 적용되는 문제
13028정성태4/13/20226883.NET Framework: 1193. (appsettings.json처럼) web.config의 Debug/Release에 따른 설정 적용
13027정성태4/12/20227147.NET Framework: 1192. C# - 환경 변수의 변화를 알리는 WM_SETTINGCHANGE Win32 메시지 사용법파일 다운로드1
13026정성태4/11/20228703.NET Framework: 1191. C 언어로 작성된 FFmpeg Examples의 C# 포팅 전체 소스 코드 [3]
13025정성태4/11/20228054.NET Framework: 1190. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 vaapi_encode.c, vaapi_transcode.c 예제 포팅
13024정성태4/7/20226556.NET Framework: 1189. C# - 런타임 환경에 따라 달라진 AppDomain.GetCurrentThreadId 메서드
13023정성태4/6/20226856.NET Framework: 1188. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 transcoding.c 예제 포팅 [3]
13022정성태3/31/20226754Windows: 202. 윈도우 11 업그레이드 - "PC Health Check"를 통과했지만 여전히 업그레이드가 안 되는 경우 해결책
13021정성태3/31/20226939Windows: 201. Windows - INF 파일을 이용한 장치 제거 방법
13020정성태3/30/20226693.NET Framework: 1187. RDP 접속 시 WPF UserControl의 Unloaded 이벤트 발생파일 다운로드1
13019정성태3/30/20226656.NET Framework: 1186. Win32 Message를 Code로부터 메시지 이름 자체를 구하고 싶다면?파일 다운로드1
13018정성태3/29/20227180.NET Framework: 1185. C# - Unsafe.AsPointer가 반환한 포인터는 pinning 상태일까요? [5]
13017정성태3/28/20226962.NET Framework: 1184. C# - GC Heap에 위치한 참조 개체의 주소를 알아내는 방법 - 두 번째 이야기 [3]
13016정성태3/27/20227848.NET Framework: 1183. C# 11에 추가된 ref 필드의 (우회) 구현 방법파일 다운로드1
13015정성태3/26/20229183.NET Framework: 1182. C# 11 - ref struct에 ref 필드를 허용 [1]
13014정성태3/23/20227753VC++: 155. CComPtr/CComQIPtr과 Conformance mode 옵션의 충돌 [1]
13013정성태3/22/20226060개발 환경 구성: 641. WSL 우분투 인스턴스에 파이썬 2.7 개발 환경 구성하는 방법
13012정성태3/21/20225388오류 유형: 803. C# - Local '...' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
13011정성태3/21/20226908오류 유형: 802. 윈도우 운영체제에서 웹캠 카메라 인식이 안 되는 경우
13010정성태3/21/20225831오류 유형: 801. Oracle.ManagedDataAccess.Core - GetTypes 호출 시 "Could not load file or assembly 'System.DirectoryServices.Protocols...'" 오류
... 16  17  18  19  20  21  22  23  [24]  25  26  27  28  29  30  ...