Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi everybody

I'm new to registry programming with c#
I have a code, this has not any error but it's not working!

I want to disable Hibernate on windows 8.1 Pro N

what's wrong here?


C#
private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                RegistryKey mykey = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Control\\Power", true);
                mykey.SetValue("HibernateEnabled", 0);
                mykey.Close();

            }
            catch { }
        }






thanks a lot :)
Posted
Updated 9-Oct-15 1:22am
v2
Comments
CHill60 9-Oct-15 7:34am    
"not working" is not helpful. What happens when you run it?
Try putting something in the catch statement rather than just invisibly swallowing exceptions.

Are you running this code with Admin rights?
Does that registry key exist in the 32-bit registry hive?
Which version of .NET are you running with (it could affect the solution)
amir.nazarizadeh 9-Oct-15 7:41am    
thanks for your answer
it's run but can not change the value from 1 to 0 !!!
CHill60 9-Oct-15 7:44am    
If you've put something in the catch statement are you getting an error reported?
Put a breakpoint on mykey.SetValue - check the value of mykey, is it null?
amir.nazarizadeh 9-Oct-15 7:51am    
it says requested registry not allowed

i think I should open this with admin permission but I don't know how to do that!

1 solution

The chances are that you need admin permission to change the SYSTEM area of the registry and your modification is being rejected as a result.

This is a good example of why swallowing exceptions is a bad idea: you have no idea there is a problem, or any details about it, just that the code doesn't work.

Change your catch:
C#
catch (Exception ex)
   {
   Debug.WriteLine(ex.Message);
   }
And it will tell you what the problem is.

Almost certainly, it's an authorization problem. This may be a better way to do it: https://social.msdn.microsoft.com/Forums/vstudio/en-US/386e0268-8986-4e49-8023-f9ae2e2689ab/disabling-hibernation?forum=csharpgeneral[^]
 
Share this answer
 
Comments
amir.nazarizadeh 9-Oct-15 7:53am    
thanks for your answer

it says requested registry not allowed

I think I should open it with admin permission but I dont't know how to do that :(
OriginalGriff 9-Oct-15 8:00am    
It means elevating your app - which means going through UAC - which is a PITA. You may find the other method I linked to easier!

See here for elevation: http://stackoverflow.com/questions/133379/elevating-process-privilege-programatically

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900