아래 그림과 같이 특정 registry의 정보가 바뀌었을 경우 그 내용을 event로 전달받을 수 있게 해 주는 프로그램
특정 application을 작성한 후 config 정보가 변경될 경우 바로 반영되는 작업을 하기에 매우 적당할 듯
..more
>접기
Introduction
The Windows API provides a function RegNotifyChangeKeyValue
, which notifies the caller about changes to attributes or the content of a specified registry key.
Unfortunately, this function is not provided by Microsoft.Win32.RegistryKey
class. Because I needed that functionality, I've written a simple wrapper class.
Usage
The usage of this is straight forward. First you have to instantiate a RegistryMonitor
object. You set its RegistryKey
property and subscribe to the monitor's RegChanged
event. Now you may start the monitoring by calling Start()
. This creates an internal thread running in an endless loop. In this loop, the thread waits for both an event fired by RegNotifyChangeKeyValue
and the terminate event, which is set by the Stop()
method. Whenever the registry key changes, the RegChanged
event is fired.
Example
Here's a console sample monitoring HKCU\Environment (that's where the current user's environment variables are stored):
public class MonitorSample{ static void Main() { RegistryMonitor monitor = new RegistryMonitor(); monitor.RegistryKey = Registry.CurrentUser.OpenSubKey(@"Environment", false); monitor.RegChanged += new EventHandler(OnRegChanged); monitor.Start(); while(true); } private void OnRegChanged(object sender, EventArgs e) { Console.WriteLine("registry key has changed"); }}
Provided with this article is another demo, which is a WinForm application (however, a VS.NET 2003 solution).
Points of interest
The implementation is pretty straightforward. One interesting point is the access to the registry handle. The RegNotifyChangeKeyValue
expects a registry handle, but, unfortunately, the handle is a private member of RegistryKey
. Well, reflection is your friend:
public static IntPtr GetRegistryHandle(RegistryKey registryKey){ Type type = registryKey.GetType(); FieldInfo fieldInfo = type.GetField("hkey", BindingFlags.Instance | BindingFlags.NonPublic); return (IntPtr)fieldInfo.GetValue(registryKey);}
History
08-Jul-2003 | Initial release |
About Thomas Freudenberg
| Click here to view Thomas Freudenberg's online profile. |
출처 : http://www.codeproject.com/csharp/registrymonitor.asp