Download demo project - 2.57 Kb
Introduction
Want to protect your source code? Using this code will prevent the vast majority of users from right-clicking over a page and choosing "View source", or right-clicking over an image and saving it.<o:p>
Some times there might be the requirement to disable the pop up menu on click of right button.<o:p>
<o:p>
Programmers may need to disable right click to prevent user from saving the images on the page or viewing the source of the page.
<o:p>
Though disabling right click is not complete solution to save the data, but it will make task difficult, or may be impossible for the rookies.<o:p>
<o:p>
I searched on a net for the solution to this problem and i got following solution.<o:p>
Method 1
In this method we add a javascript method, in this we check if click is right click or left click if it is right click then a message is displayed like "Right click disabled"<o:p>
<o:p>
<o:p>
<script language="javascript">
document.onmousedown=disableclick;
status="Right Click Disabled";
Function disableclick(e)
{
if(event.button==2)
{
alert(status);
return false;
}
}
</script>
But in this solution if you click the right click it displays the message <o:p>
“Right click disabled”.<o:p>
<o:p>
<o:p>
If we want to remove the messegebox then this solution do not work.<o:p>
I am having another simple solution to achieve the same result and also it does not show the messegebox.<o:p>
<o:p>
Method 2
In this method we set the oncontextmenu="return false" in the body part of the page
so body part will look like
<body oncontextmenu="return false">
...
</body>
So whenever user clicks the right mouse button nothing will happen, no message no context menu.<o:p>
<o:p>
Sometimes there might be requirement to disable the right click on specific control to achive this we have to follow these steps.<o:p>
1. remove added code in body (i.e. oncontextmenu=”return false”)<o:p>
2. Add one table and in its row add the control e.g. datagrid control<o:p>
3. put the oncontextmenu=”return false” in the <tr> for that control<o:p>
<o:p>
So code will look like this<o:p>
<Body>
<Table>
<tr oncontextmenu="return false">
<td>
<asp:datagrid id="dgGrid1">---</asp:datagrid>
</td>
</tr>
</Table>
</Body>
So by this method context menu on the right click of right mouse click can be disabled. <o:p>
<o:p>