Wednesday, June 15, 2011

Disabling cut, copy, paste, right click and context menu in a textbox on aspx page

In this tutorial you will learn how to disable cut, copy, paste, right click and context menu in asp:textbox. Sometimes due to security point of view you may want to do this. It's quite simple, I often see that developers write javascript code to disable the cut, copy, paste in textbox either textbox is input or server side asp:textbox.
I will not use any single line of javascript code to achieve what I want. Now let's have a look over how to do so.

Disabling cut, copy, paste, right click and context menu in a textbox

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Create div element dynamically using javascript</title>
<style type="text/css">
.myDivClass
{
color: #999;
padding: 10px;
width: 250px;
height: 150px;
border: solid 1px #666;
}
</style>
<script type="text/javascript" language="javascript">
function CreateDivElement() {
var divElement = document.createElement("div");
divElement.id = "myDiv";
divElement.className = "myDivClass";
divElement.innerHTML = "Hello World!";
document.body.appendChild(divElement);
}
function disableCopy() {
    alert("You cannot perform Copy");
    return false;
}
function disablePaste() {
    alert("You cannot perform Paste");
    return false;
}
function disableCut() {
    alert("You cannot perform Cut");
    return false;
}
function disableContextMenu() {
    alert("You cannot perform right click via mouse as well as keyboard");
    return false;
}
 
</script>
</head>
<form runat="server" id="form1">
<body>
<div>
<input id="myBtn" type="button" value="Click Me" onclick="CreateDivElement();" />
<asp:TextBox ID="TextBox1" runat="server" oncopy="return false" onpaste="return false" oncut="return false" oncontextmenu="return false">  
</asp:TextBox>  
<asp:TextBox ID="txtName" runat="server" oncopy="return disableCopy()" onpaste="return disablePaste()" oncut="return disableCut()" oncontextmenu="return disableContextMenu()">  
</asp:TextBox>  
</div>
</body>
</form>
</html>

output:


 copy

0 comments:

Post a Comment