Click here to Skip to main content
15,891,864 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
im a beginner in c#. i've this problem where i try to run some coding that i take from a blog in internet. when i run the code, it says NullReferenceException was unhandled. i dont know how to solve the error.

this is the coding:

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.IO;

namespace Anticopy
{   
   
   
    public partial class Form1 : Form
    {
        // Import user32.dll to call logoff API
        [DllImport("user32.dll")]       
        public static extern int ExitWindowsEx(int uFlags, int dwReason);
       
        public void anticopy()
        {
            if (chkDragDrop.Checked == true)
            {
                DialogResult u;
                u = MessageBox.Show("To Activate \nLog Off Required Now", "Log Off", MessageBoxButtons.YesNo);
                //if user Press Yes
                if (u == DialogResult.Yes)
                {
                    try
                    {

                        //Registry Value Change for disabling drag drop
                        RegistryKey dd = Registry.CurrentUser.OpenSubKey("Control Panel\\Desktop", true);
                        dd.SetValue("DragHeight", "9999");
                        dd.SetValue("Dragwidth", "9999");

                        //Application Register Itself To Launch On Next Window Logon for one time only
                        string currentpath = Path.GetDirectoryName(Application.ExecutablePath);
                        RegistryKey startup = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce", true);
                        startup.SetValue("anticopy", currentpath + "\\Anticopy.exe");

                        //Log Off Window
                        ExitWindowsEx(0, 0);
                    }
                    catch (Exception ui)
                    {
                        MessageBox.Show("" + ui);
                    }
                }
            }
            else
            {
                if (chkSendTo.Checked == true)
                    sendto ("disable");

                btnStop.Enabled = true;
                btnStart.Enabled = false;

                this.Hide();
                timer1.Enabled = true;
                NotifyMe();
                label1.Text = "Just Minimize Me or Stop";
            }


        }

        private void sendto(string stat)
        {   // try and catch: cause window-xp use "Send To" and Vista,Window7 Use "SendTo"

            try
            {
                RegistryKey sendto =
                Registry.ClassesRoot.OpenSubKey("AllFilesystemObjects\\shellex\\ContextMenuHandlers\\SendTo", true);
                if (stat == "disable")
                    sendto.SetValue(null, "");
                else
                    sendto.SetValue(null, "{7BA4C740-9E81-11CF-99D3-00AA004AE837}");
            }
            catch
            {
                RegistryKey sendto = Registry.ClassesRoot.OpenSubKey("AllFilesystemObjects\\shellex\\ContextMenuHandlers\\Send To", true);
                if (stat == "disable")
                    sendto.SetValue(null, ""); //this is where it says NullReferenceException was unhandled
                else
                    sendto.SetValue(null, "{7BA4C740-9E81-11CF-99D3-00AA004AE837}");
            }

        }

        private void NotifyMe()
        {

            TrayIcon.BalloonTipTitle = "Anticopy";
            TrayIcon.BalloonTipText = "Anticopy Running..";
            TrayIcon.ShowBalloonTip(1);
            TrayIcon.ContextMenuStrip = contextMenuStrip1;
        }
    
       
        public Form1()
        {
            InitializeComponent();

        }        
        
        private void start_Click(object sender, EventArgs e)
        {
            anticopy();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            btnStop.Enabled = false;
            try
            {
                RegistryKey dd = Registry.CurrentUser.OpenSubKey("Control Panel\\Desktop", true);
                string DragHeight = dd.GetValue("DragHeight").ToString();
                string Dragwidth = dd.GetValue("Dragwidth").ToString();
                if (DragHeight == "4" && Dragwidth == "4") { }

                else
                {//if Drag Height & Width has Not default value then reset to default value
                    dd.SetValue("DragHeight", "4");
                    dd.SetValue("Dragwidth", "4");
                    chkSendTo.Checked = true;
                    anticopy();
                    btnStart.Enabled = false;
                }
            }
            catch { MessageBox.Show("Run Me As Admin"); this.Close(); }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
           Clipboard.Clear();
        }

        private void chkDragDrop_CheckedChanged(object sender, EventArgs e)
        {
            if (chkDragDrop.Checked == true)
            {
                label1.Text = "Logoff Required";
            }
            else
            {
                label1.Text = "";
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            sendto ("enable");
            btnStart.Enabled = true;
            btnStop.Enabled = false;
            label1.Text = "";
            MessageBox.Show("If Drag Drop Were Disable\nActivate On Next Window LogOn");
        }
  
        private void Form1_Resize(object sender, EventArgs e)
        {
                       if( WindowState == FormWindowState.Minimized)
            Hide();
        }
       
        private void MyNotify_DoubleClick(object sender, EventArgs e)
        {
            Show();
            WindowState = FormWindowState.Normal;

        }

        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TrayIcon.Dispose();
            Application.Exit();

        }

        private void restoreToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Show();
            WindowState = FormWindowState.Normal;

        }
          
    }
}



i still cant find the solution. sorry if my information not complete. im new to dis site. much appreciate for your help. thank you.
Posted
Updated 28-Jul-11 7:12am
v5
Comments
Kim Togo 28-Jul-11 2:24am    
Please use "Add Comment" and not "Add a Solution" when replying to a Solution.

This is because RegistryKey.OpenSubKey returns null if the sub-key is not found, see http://msdn.microsoft.com/en-us/library/z9f66s0a.aspx[^]. So sendto could be null.

You should do the following: 1) makes sure the registry key exists, use Regedit.EXE; 2) run you code under debugger to see what's wrong; if you did it in first place, you would not have to ask this question; 3) in your code, check up the instance of RegistryKey for null and device appropriate action, throw exception, for example.

—SA
 
Share this answer
 
Comments
Kim Togo 28-Jul-11 2:23am    
From OP

thank you for the reference! :)
Abhinav S 28-Jul-11 13:01pm    
Perfect. 5.
Sergey Alexandrovich Kryukov 1-Aug-11 0:50am    
Thank you, Abhinav.
--SA
First of all, you place the same code that you are trying to execute into catch. If something is wrong in try you should handle it in catch. With the code that you are doing up there is not correct.

The exception that you are getting indicates that; "you are trying to access member fields or function types on an object reference that points to null."

Have you debugged it and checked the values that you are having in your code?

A better understanding for this exception check this link[^].

For a proper try-catch block check this msdn link[^]

-or-

this link[^] helps you in a more simplified way.

Good luck,
 
Share this answer
 
v2
Comments
Kim Togo 28-Jul-11 2:23am    
From OP

thank you for the reference! :)

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