How to Prevent installed language on machine from changing - c#

I need to disable the language change using alt + shift keys for a text box. I have the function which change the currentCulture but pressing Alt + Shift always switch to the next language even if I set it on the keydown or keyup event.

You must detect Windows OS input language changes and change it to your desired language for your application when it has focus.
So read following articles for detecting Windows OS input language changes:
1. http://msdn.microsoft.com/en-us/library/ms644990(VS.85).aspx
2. http://www.codeproject.com/KB/system/TrayMe.aspx
And then use from following codes to achieve to your goal:
/// <summary>
/// Changing Current Input Language to a next installed language
/// </summary>
public void ChangeInputLanguage()
{
// Nothing to do if there is only one Input Language supported:
if (InputLanguage.InstalledInputLanguages.Count == 1)
return;
// Get index of current Input Language
int currentLang = InputLanguage.InstalledInputLanguages.IndexOf(InputLanguage.CurrentInputLanguage);
// Calculate next Input Language
InputLanguage nextLang = ++currentLang == InputLanguage.InstalledInputLanguages.Count ?
InputLanguage.InstalledInputLanguages[0] : InputLanguage.InstalledInputLanguages[currentLang];
// Change current Language to the calculated:
ChangeInputLanguage(nextLang);
}
/// <summary>
/// Changing current Input Language to a new one passed in the param
/// </summary>
/// <param name="ISOLang">ISO Culture name string code e.g. "en" for English</param>
public void ChangeInputLanguage(string ISOLang)
{
// Convert ISO Culture name to InputLanguage object. Be aware: if ISO is not supported
// ArgumentException will be invoked here
InputLanguage nextLang = InputLanguage.FromCulture(new System.Globalization.CultureInfo(ISOLang));
ChangeInputLanguage(nextLang);
}
/// <summary>
/// Changing current Input Language to a new one passed in the param
/// </summary>
/// <param name="LangID">Integer Culture code e.g. 1033 for English</param>
public void ChangeInputLanguage(int LangID)
{
// Convert Integer Culture code to InputLanguage object. Be aware: if Culture code is not supported
// ArgumentException will be invoked here
InputLanguage nextLang = InputLanguage.FromCulture(new System.Globalization.CultureInfo(LangID));
ChangeInputLanguage(nextLang);
}
/// <summary>
/// Changing current Input Language to a new one passed in the param
/// </summary>
/// <param name="InputLang">New Input Language as InputLanguage object</param>
public void ChangeInputLanguage(InputLanguage InputLang)
{
// Check is this Language really installed. Raise exception to warn if it is not:
if (InputLanguage.InstalledInputLanguages.IndexOf(InputLang) == -1)
throw new ArgumentOutOfRangeException();
// InputLAnguage changes here:
InputLanguage.CurrentInputLanguage = InputLang;
}

Related

Mixed Console / Forms application always opens second console

I'm writing an app that's primarily intended to be a Console application, but some of its functions open / use forms to do their work.
This all works fine, except that when it's called, the app always opens an ADDITIONAL console window, into which all of it's console operations and interactions are performed (this unwanted second window then closes upon program termination). This is wholly unwanted behaviour, but I haven't a clue as to why this second window is being spawned, nor why the application insists on only writing/reading from THAT window, instead of the one from which it was called...
Here's the content of my Program.cs file...
using System;
using System.Diagnostics;
using System.Windows.Forms;
using CobblestoneMgmt.Forms;
using ConfigManagement;
using CodeLibrary.ConsoleFunctions;
using Xtensions.CmdlineArgumentMgmt;
namespace AppMgmt
{
static class Program
{
/// <summary>The main entry point for the application.</summary>
[STAThread]
static void Main(string[] _args)
{
ArgumentsMgt args = new ArgumentsMgt(_args);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (args.Count == 0)
{
// Run it as a WindowsForms application.
Application.Run(new AppManagement());
}
else
{
Console.OutputEncoding = System.Text.Encoding.Unicode;
//Run it as a Console application.
if (args.HasSwitch("install"))
{
if ((args.Count==1) || args["install"].HasValue("guided") || args.HasSwitch("guided"))
Application.Run(new Installation());
if (args.HasSwitch("regedit"))
{
if (args["regedit"].HasValue("ShowConfig"))
{
IniFile config = IniFile.FetchResourceFile("AppMgmt.ExternalResources.DefaultConfig.ini");
Con.Write(config.ToString());
}
}
}
Con.WaitPrompt();
}
}
}
}
Although I don't think it's relevant, the "Con" interface used here is simply an intermediate class for making Console writes more utilitarian / friendly:
using System;
namespace CodeLibrary.ConsoleFunctions
{
/// <summary>Simple static routines to facilitate writing text to the Console in color more efficiently.</summary>
public static class Con
{
#region Methods
/// <summary>Output specified text to the Console at the current cursor position, in the specified colours.</summary>
/// <param name="data">The text to write.</param>
/// <param name="fore">The foreground colour to use (default = LightGray).</param>
/// <param name="back">The background colour to use (default = black).</param>
public static void Write(string data, ConsoleColor fore, ConsoleColor back = ConsoleColor.Black)
{
CliColor store = CliColor.CaptureConsole();
Console.ForegroundColor = fore;
Console.BackgroundColor = back;
Console.Write(data);
store.ToConsole();
}
public static void Write(string data, CliColor color = null) =>
Write(data, ((color is null) ? CliColor.Default.Fore : color.Fore), ((color is null) ? CliColor.Default.Back : color.Back));
/// <summary>Output specified text to the Console at the current cursor position, in the specified colours,followed by a newline.</summary>
/// <param name="data">The text to write.</param>
/// <param name="fore">The foreground colour to use (default = LightGray).</param>
/// <param name="back">The background colour to use (default = black).</param>
public static void WriteLn(string data, ConsoleColor fore = ConsoleColor.Gray, ConsoleColor back = ConsoleColor.Black)
{
Write(data, fore, back);
Console.WriteLine();
}
/// <summary>Sends text to the Console with a section highlighted in a different colour.</summary>
/// <param name="first">The first section of text to write in the basic foreground colour.</param>
/// <param name="second">The second section of text to write in the highlight colour.</param>
/// <param name="third">An optional third section of text to write, back in the basic foreground colour.</param>
/// <param name="fore">The foreground colour to use for the first and third strings (default = LightGray).</param>
/// <param name="highlight">The foreground colour to use for the second string (default = White)</param>
/// <param name="back">The background colour to use throughout (default = black).</param>
public static void Highlight(string first, string second, string third = "", ConsoleColor fore = ConsoleColor.Gray, ConsoleColor highlight = ConsoleColor.White, ConsoleColor back = ConsoleColor.Black)
{
Write(first, fore, back);
Write(second, highlight, back);
Write(third, fore, back);
}
/// <summary>Sends text to the Console with a section highlighted in a different colour and followed with a newline.</summary>
/// <param name="first">The first section of text to write in the basic foreground colour.</param>
/// <param name="second">The second section of text to write in the highlight colour.</param>
/// <param name="third">An optional third section of text to write, back in the basic foreground colour.</param>
/// <param name="fore">The foreground colour to use for the first and third strings (default = LightGray).</param>
/// <param name="highlight">The foreground colour to use for the second string (default = White)</param>
/// <param name="back">The background colour to use throughout (default = black).</param>
public static void HighlightLn(string first, string second, string third = "", ConsoleColor fore = ConsoleColor.Gray, ConsoleColor highlight = ConsoleColor.White, ConsoleColor back = ConsoleColor.Black) =>
Highlight(first, second, third + "\r\n", fore, highlight, back);
/// <summary>Implements a basic "Press Any Key" pause.</summary>
/// <param name="withEsc">If set to TRUE, adds the text "(or [ESC] to quit)." to the prompt.</param>
/// <param name="fore">The foreground colour to apply to the base text.</param>
/// <param name="back">The background colour to use.</param>
/// <param name="highlight">Optional highlight colour to apply to the "[ESC]" portion of the output.</param>
/// <returns></returns>
public static char WaitPrompt(int indent = 0, bool withEsc = false, ConsoleColor fore = ConsoleColor.Gray, ConsoleColor back = ConsoleColor.Black, ConsoleColor highlight = ConsoleColor.White)
{
Write("Press any key...".PadLeft(indent,' '), fore, back);
if (withEsc) Highlight("(or ", "[ESC]", " to quit).", fore, highlight, back);
char result = Console.ReadKey().KeyChar;
// Using \r's, without a \n causes the Cursor to return to column 1, of the same line. This effectively clears
// the prompt and leaves the cursor where it would have been if the prompt hadn't come up.
Write("\r \r", fore, back);
return result;
}
#endregion
}
}
All I want is for the application to work within the confines of the Console window from which it is invoked, how do I make it stop creating / accessing the second instance of it?
I had problems recreating your problem but check if your application is set to ConsoleApplication
Right click on the project in solution explorer. Go to Properties set your output type to Console Application.
Screenshot

C#/Bing Maps Win8.1 - Getting current quadkey(s) as string

I have a map which I am trying to add a layer to, which the layer server supports the XYZoomLevel standard, creating a problem.
In order to begin the process of converting a quadkey to an XYZ, I need to get the current quadkey(s) which would be used to render the map outputted to a string and changed every time the key changes. How do I get the quad key as a string value?
Here is sample code that allows you to add a layer, see
http://msdn.microsoft.com/en-us/library/hh846495.aspx:
MapTileLayer tileLayer = new MapTileLayer();
tileLayer.TileSource = "http://www.microsoft.com/maps/isdk/ajax/layers/lidar/{quadkey}.png";
map.TileLayers.Add(tileLayer);
map.SetView(new Location(48.03, -122.42), 11, MapAnimationDuration.None);
If you want to use a different uri scheme, you can use an alternative way by using the GetTileUri() method of the MapTileLayer class, that you will set with your own code to compose the uri. You can then convert the quadkey to xyz or the contrary.
Here a sample code where you use the method:
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
Bing.Maps.MapTileLayer layer = new Bing.Maps.MapTileLayer();
layer.GetTileUri += layer_GetTileUri;
this.map.TileLayers.Add(layer);
}
private async void layer_GetTileUri(object sender, Bing.Maps.GetTileUriEventArgs e)
{
e.Uri = this.ComposeMyCustomUri(e);
}
Here, e is a specific parameter object of type GetTileUriEventArgs, see:
http://msdn.microsoft.com/en-us/library/jj672952.aspx
If you want to go from XYZ to quadkey, you can do it using this C# code:
/// <summary>
/// Converts tile XY coordinates into a QuadKey at a specified level of detail.
/// </summary>
/// <param name="tileX">Tile X coordinate.</param>
/// <param name="tileY">Tile Y coordinate.</param>
/// <param name="levelOfDetail">Level of detail, from 1 (lowest detail)
/// to 23 (highest detail).</param>
/// <returns>A string containing the QuadKey.</returns>
public static string TileXYToQuadKey(int tileX, int tileY, int levelOfDetail)
{
StringBuilder quadKey = new StringBuilder();
for (int i = levelOfDetail; i > 0; i--)
{
char digit = '0';
int mask = 1 << (i - 1);
if ((tileX & mask) != 0)
{
digit++;
}
if ((tileY & mask) != 0)
{
digit++;
digit++;
}
quadKey.Append(digit);
}
return quadKey.ToString();
}
Here is a more complete link from which the code is extracted, MSDN: http://msdn.microsoft.com/en-us/library/bb259689.aspx

Why Could My Application Trial Not be Working in the Marketplace

I recently have released a small application with a trial to the Windows Phone Marketplace, but my application is not working as expected. I have followed http://code.msdn.microsoft.com/Trial-Experience-Sample-c58f21af when making my trial, so that I can call the current 'LicenseInformation' state and block a feature or not depending on the current application's license state. According to the sample application, The LicenseMode property returns a value from the LicenseModes enum (Full, MissingOrRevoked, or Trial) so that your app code needs to check only a single value. There’s also a convenient Boolean IsFull property. Whenever the license mode has changed, or it is likely to have changed, TrialExperienceHelper raises its LicenseChanged event and your app code can handle that event to query LicenseMode or IsFull again. Then, your app can control the availability of features, ads, and your Buy UI as needed.
In my application I have a click event in which I would like to perform an action based on the current LicenseInformation state and upon a count (the count being the number of times an image is saved with particular aspects applied).
Settings.SavedCount.Value records the number of times the save button is clicked, and if the count is above 100 and the application is in trial mode I would like to ask the user if they would like to upgrade, otherwise if the count is less than 100 while the application is in trial mode or if the license is in full mode then the user is allowed to continue with the save process (hopefully that makes logical sense).
void saveButton_Click(object sender, EventArgs e)
{
Settings.SavedCount.Value += 1;
if (TrialViewModel.LicenseModeString == "Trial" && Settings.SavedCount.Value > 100)
{
MessageBoxResult result = MessageBox.Show("You have saved over 100 items! Would you like to continue?", "Congratulations!", MeesageBoxButton.OKCancel);
switch (result)
{
case MessageBoxResult.OK:
//A command takes a parameter so pass null
TrialViewModel.BuyCommand.Execute(null);
break;
case MessageBoxResult.Cancel:
editPagePivotControl.SelectedIndex = 0;
break;
}
}
else if ((TrialViewModel.LicenseModeString == "Trial" && Settings.SavedCount.Value <= 100) || (TrialViewModel.LicenseModeString == "Full")
{
PerformSaveAsync();
}
}
}
When testing in Debug mode and with the sample implementation from the msdn website, the Trial and Full implementations worked properly, and then when in Release mode the license was listed as MissingOrRevoked which I assumed would be called correctly in the marketplace. What is ACTUALLY occuring when i have downloaded the app in the marketplace under both trial and full modes is that the PerformSaveAsync() method is never being called (which ultimately saves the new image and disables the button) and I can use the new image elsewhere. I am having trouble figuring out what the issue may be?
EDIT** In researching I came across http://msdn.microsoft.com/en-us/library/aa691310(v=vs.71).aspx which states that The operation x && y corresponds to the operation x & y, except that y is evaluated only if x is true. and `•The operation x || y corresponds to the operation x | y, except that y is evaluated only if x is false/' . Would this be the cause of the issues? If so, how should they be fixed?
Edit 2** Addtion of TrialViewModel and TrialExperienceHelper.cs for additional info
TrialViewModel
TrialViewModel
#region fields
private RelayCommand buyCommand;
#endregion fields
#region constructors
public TrialViewModel()
{
// Subscribe to the helper class's static LicenseChanged event so that we can re-query its LicenseMode property when it changes.
TrialExperienceHelper.LicenseChanged += TrialExperienceHelper_LicenseChanged;
}
#endregion constructors
#region properties
/// <summary>
/// You can bind the Command property of a Button to BuyCommand. When the Button is clicked, BuyCommand will be
/// invoked. The Button will be enabled as long as BuyCommand can execute.
/// </summary>
public RelayCommand BuyCommand
{
get
{
if (this.buyCommand == null)
{
// The RelayCommand is constructed with two parameters - the action to perform on invocation,
// and the condition under which the command can execute. It's important to call RaiseCanExecuteChanged
// on a command whenever its can-execute condition might have changed. Here, we do that in the TrialExperienceHelper_LicenseChanged
// event handler.
this.buyCommand = new RelayCommand(
param => TrialExperienceHelper.Buy(),
param => TrialExperienceHelper.LicenseMode == TrialExperienceHelper.LicenseModes.Trial);
}
return this.buyCommand;
}
}
public string LicenseModeString
{
get
{
return TrialExperienceHelper.LicenseMode.ToString()/* + ' ' + AppResources.ModeString*/;
}
}
#endregion properties
#region event handlers
// Handle TrialExperienceHelper's LicenseChanged event by raising property changed notifications on the
// properties and commands that
internal void TrialExperienceHelper_LicenseChanged()
{
this.RaisePropertyChanged("LicenseModeString");
this.BuyCommand.RaiseCanExecuteChanged();
}
#endregion event handlers
TrialExperienceHelper.cs
#region enums
/// <summary>
/// The LicenseModes enumeration describes the mode of a license.
/// </summary>
public enum LicenseModes
{
Full,
MissingOrRevoked,
Trial
}
#endregion enums
#region fields
#if DEBUG
// Determines how a debug build behaves on launch. This field is set to LicenseModes.Full after simulating a purchase.
// Calling the Buy method (or navigating away from the app and back) will simulate a purchase.
internal static LicenseModes simulatedLicMode = LicenseModes.Trial;
#endif // DEBUG
private static bool isActiveCache;
private static bool isTrialCache;
#endregion fields
#region constructors
// The static constructor effectively initializes the cache of the state of the license when the app is launched. It also attaches
// a handler so that we can refresh the cache whenever the license has (potentially) changed.
static TrialExperienceHelper()
{
TrialExperienceHelper.RefreshCache();
PhoneApplicationService.Current.Activated += (object sender, ActivatedEventArgs e) => TrialExperienceHelper.
#if DEBUG
// In debug configuration, when the user returns to the application we will simulate a purchase.
OnSimulatedPurchase();
#else // DEBUG
// In release configuration, when the user returns to the application we will refresh the cache.
RefreshCache();
#endif // DEBUG
}
#endregion constructors
#region properties
/// <summary>
/// The LicenseMode property combines the active and trial states of the license into a single
/// enumerated value. In debug configuration, the simulated value is returned. In release configuration,
/// if the license is active then it is either trial or full. If the license is not active then
/// it is either missing or revoked.
/// </summary>
public static LicenseModes LicenseMode
{
get
{
#if DEBUG
return simulatedLicMode;
#else // DEBUG
if (TrialExperienceHelper.isActiveCache)
{
return TrialExperienceHelper.isTrialCache ? LicenseModes.Trial : LicenseModes.Full;
}
else // License is inactive.
{
return LicenseModes.MissingOrRevoked;
}
#endif // DEBUG
}
}
/// <summary>
/// The IsFull property provides a convenient way of checking whether the license is full or not.
/// </summary>
public static bool IsFull
{
get
{
return (TrialExperienceHelper.LicenseMode == LicenseModes.Full);
}
}
#endregion properties
#region methods
/// <summary>
/// The Buy method can be called when the license state is trial. the user is given the opportunity
/// to buy the app after which, in all configurations, the Activated event is raised, which we handle.
/// </summary>
public static void Buy()
{
MarketplaceDetailTask marketplaceDetailTask = new MarketplaceDetailTask();
marketplaceDetailTask.ContentType = MarketplaceContentType.Applications;
marketplaceDetailTask.Show();
}
/// <summary>
/// This method can be called at any time to refresh the values stored in the cache. We re-query the application object
/// for the current state of the license and cache the fresh values. We also raise the LicenseChanged event.
/// </summary>
public static void RefreshCache()
{
TrialExperienceHelper.isActiveCache = CurrentApp.LicenseInformation.IsActive;
TrialExperienceHelper.isTrialCache = CurrentApp.LicenseInformation.IsTrial;
TrialExperienceHelper.RaiseLicenseChanged();
}
private static void RaiseLicenseChanged()
{
if (TrialExperienceHelper.LicenseChanged != null)
{
TrialExperienceHelper.LicenseChanged();
}
}
#if DEBUG
private static void OnSimulatedPurchase()
{
TrialExperienceHelper.simulatedLicMode = LicenseModes.Full;
TrialExperienceHelper.RaiseLicenseChanged();
}
#endif // DEBUG
#endregion methods
#region events
/// <summary>
/// The static LicenseChanged event is raised whenever the value of the LicenseMode property has (potentially) changed.
/// </summary>
public static event LicenseChangedEventHandler LicenseChanged;
#endregion events
If your dev builds work and the only difference is with the app being published via the store then I think it's very unlikely to be your logic.
When you submitted the app, are you sure you checked the option to be able to use the trial functionality in the app?
If you didn't check this then it won't work in a released app.
Regarding your edit, I don't see any problem with your condition, your quote is just that the operator is lazy, evaluating only what is needed to determine the result (for example when you do x&& y if x is false, x&& false=> false and x&& true==false which is the same result so it don't evaluate y).
Also like I said in your previous question even the windows phone 7 api still work on windows phone 8 so if you are creating code for both platform there is probably no need to use the new api specifically for wp8.
In this code I don't see any problem but why do you convert the LicenseModes enum to string, using the enum will add some type safety and prevent you to do some invalid comparison.
The only problem is where you set LicenseModeString or a problem inside PerformSaveAsync?

"Source pixel format is not supported by the filter" error in AForge.NET

I'm trying to apply Bradleys thresholding algorithm in Aforge
Everytime I try to process the image I get the exception below
throw new UnsupportedImageFormatException( "Source pixel format is not
supported by the filter." );
I grayscaled the image using the below method before applying the algorithm
private void button2_Click(object sender, EventArgs e)
{
Grayscale filter = new Grayscale(0.2125, 0.7154, 0.0721);
Bitmap grayImage = filter.Apply(img);
pictureBox1.Image = grayImage;
}
The code for the algorithm call
public void bradley(ref Bitmap tmp)
{
BradleyLocalThresholding filter = new BradleyLocalThresholding();
filter.ApplyInPlace(tmp);
}
I tried the sane image in image processing lab and it did work but not on my system.
Any idea what I'm doing wrong?
I've used the following code to get better information in cases like this. It doesn't fix the problem, but it at least gives more helpful information than AForge does by itself.
namespace AForge.Imaging.Filters {
/// <summary>
/// Provides utility methods to assist coding against the AForge.NET
/// Framework.
/// </summary>
public static class AForgeUtility {
/// <summary>
/// Makes a debug assertion that an image filter that implements
/// the <see cref="IFilterInformation"/> interface can
/// process an image with the specified <see cref="PixelFormat"/>.
/// </summary>
/// <param name="filterInfo">The filter under consideration.</param>
/// <param name="format">The PixelFormat under consideration.</param>
[Conditional("DEBUG")]
public static void AssertCanApply(
this IFilterInformation filterInfo,
PixelFormat format) {
Debug.Assert(
filterInfo.FormatTranslations.ContainsKey(format),
string.Format("{0} cannot process an image "
+ "with the provided pixel format. Provided "
+ "format: {1}. Accepted formats: {2}.",
filterInfo.GetType().Name,
format.ToString(),
string.Join( ", ", filterInfo.FormatTranslations.Keys)));
}
}
}
In your case, you can use it as:
public void bradley(ref Bitmap tmp)
{
BradleyLocalThresholding filter = new BradleyLocalThresholding();
filter.AssertCanApply( tmp.PixelFormat );
filter.ApplyInPlace(tmp);
}

Registry Watcher C#

I'm a newbie to WMI and I need to implement RegistryValueChangeEvent in a C# service.
I need an event handler that gets triggered each time any one of a set of registry values is changed. I want behavior similar to the FileSystemWatcher class's Changed event, but for registry values.
If there's some other technique I could use to accomplish the same task, I'd appreciate that as well. My minimum requirement is that it be a better solution than what I have now: polling every 20 seconds and comparing the registry value with the last result.
Please provide example code in your answer. If I can get an example for watching just one registry value, that would be fine.
I need a solution in .Net 2.0
Thanks.
WMI can sometimes be interesting to work with...I think I understand your question, so take a look at the code snippet below and let me know if it's what you're looking for.
// ---------------------------------------------------------------------------------------------------------------------
// <copyright file="Program.cs" company="">
//
// </copyright>
// <summary>
// Defines the WmiChangeEventTester type.
// </summary>
// ---------------------------------------------------------------------------------------------------------------------
namespace WmiExample
{
using System;
using System.Management;
/// <summary>
/// </summary>
public class WmiChangeEventTester
{
/// <summary>
/// Initializes a new instance of the <see cref="WmiChangeEventTester"/> class.
/// </summary>
public WmiChangeEventTester()
{
try
{
// Your query goes below; "KeyPath" is the key in the registry that you
// want to monitor for changes. Make sure you escape the \ character.
WqlEventQuery query = new WqlEventQuery(
"SELECT * FROM RegistryValueChangeEvent WHERE " +
"Hive = 'HKEY_LOCAL_MACHINE'" +
#"AND KeyPath = 'SOFTWARE\\Microsoft\\.NETFramework' AND ValueName='InstallRoot'");
ManagementEventWatcher watcher = new ManagementEventWatcher(query);
Console.WriteLine("Waiting for an event...");
// Set up the delegate that will handle the change event.
watcher.EventArrived += new EventArrivedEventHandler(HandleEvent);
// Start listening for events.
watcher.Start();
// Do something while waiting for events. In your application,
// this would just be continuing business as usual.
System.Threading.Thread.Sleep(100000000);
// Stop listening for events.
watcher.Stop();
}
catch (ManagementException managementException)
{
Console.WriteLine("An error occurred: " + managementException.Message);
}
}
/// <summary>
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The e.
/// </param>
private void HandleEvent(object sender, EventArrivedEventArgs e)
{
Console.WriteLine("Received an event.");
// RegistryKeyChangeEvent occurs here; do something.
}
/// <summary>
/// </summary>
public static void Main()
{
// Just calls the class above to check for events...
WmiChangeEventTester receiveEvent = new WmiChangeEventTester();
}
}
}
You really don't need WMI, as others have pointed out. I too have used RegistryMonitor with no problems.
If you need an example, there's already example code for the RegistryMonitor on the page itself. Did you scroll down to this bit on the code project:
public class MonitorSample
{
static void Main()
{
RegistryMonitor monitor = new
RegistryMonitor(RegistryHive.CurrentUser, "Environment");
monitor.RegChanged += new EventHandler(OnRegChanged);
monitor.Start();
while(true);
monitor.Stop();
}
private void OnRegChanged(object sender, EventArgs e)
{
Console.WriteLine("registry key has changed");
}
}
Are you limited to WMI?
If not you can use RegNotifyChangeKeyValue wrappers like RegistryMonitor
You'll need to utilize WMI for it. See http://msdn.microsoft.com/en-us/library/aa393035.aspx

Categories

Resources