Saving Clipboard PrintScreen to Image File in C# - c#

I am trying to use Visual Studio C# to printscreen, then save the screen capture to a file.
Currently, I am having problems reading from the clipboard.
I have tried using both of the following lines to save a screen capture to the clipboard:
SendKeys.SendWait("+{PRTSC}");
SendKeys.SendWait("{PRTSC}");
However, when I try to save the image using the following lines, I get a Null Reference Exception.
How to do resolve this?
My code below
markup code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Welcome to ASP.NET!
</h2>
1. Copy image data into clipboard or press Print Screen
<br />
2. Press Ctrl+V (page/iframe must be focused):
<br />
<br />
<canvas style="border: 1px solid grey;" id="cc" width="200" height="200">
<script type="text/javascript">
var canvas = document.getElementById("cc");
var ctx = canvas.getContext("2d");
//=== Clipboard ===============================
window.addEventListener("paste", pasteHandler); //chrome
//handler
function pasteHandler(e) {
if (e.clipboardData == false) return false; //empty
var items = e.clipboardData.items;
if (items == undefined) return false;
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf("image") == -1) continue; //not image
var blob = items[i].getAsFile();
var URLObj = window.URL || window.webkitURL;
var source = URLObj.createObjectURL(blob);
paste_createImage(source);
}
}
//draw pasted object
function paste_createImage(source) {
var pastedImage = new Image();
pastedImage.onload = function () {
ctx.drawImage(pastedImage, 0, 0);
}
pastedImage.src = source;
}
</script>
</canvas>
<br />
</div>
<div>
<asp:Button ID="btn" runat="server" OnClick="btn_Click" Text="Go" />
</div>
</form>
</body>
</html>
code-behind
protected void btn_Click(object sender, EventArgs e)
{
var path = new[] { #"C:\Users\A\source\repos\CopyPaste\public",
#"C:\Users\A\source\repos\CopyPaste\public" }.First(p => Directory.Exists(p));
var prefix = "css-social-media-icon-list";
var fileName = Enumerable.Range(1, 100)
.Select(n => Path.Combine(path, $"{prefix}-{n}.png"))
.First(p => !File.Exists(p));
Clipboard.GetImage().Save(fileName, ImageFormat.Png);
Clipboard.SetText($"![image](/public/{Path.GetFileName(fileName)})");
}

I hope this helping... following this example

Related

Cant access asp labels properties using c# in aspx page

I am trying to access an asp label field properties from c# code, and it keeps giving me the error:
The name 'lblTest' does not exist in the current context.
This is happening on my login.aspx page when calling the 'ValidateEmail' method.
There are no associated .cs files, just a login.master page.
I have a business request requiring me to modify someone elses code for enhancement, and I am guessing this has something to do with the existing content structure of .
I have tried placing this in master file, outside of the structure, etc. Still no joy.
Here is the login.aspx code:
<%# Page Language="C#" MasterPageFile="~/Masters/Login.master" AutoEventWireup="true" Culture="auto" UICulture="auto" EnableEventValidation="false" %>
<%# Import Namespace="Internal.Platform.Diagnostics" %>
<%# Import Namespace="Internal.Web" %>
<%# Import Namespace="Internal.Trial" %>
<%# Register Assembly="Internal.Web.Controls" Namespace="Internal.Web.Controls" TagPrefix="Internal" %>
<%# Register Assembly="Internal.Web.Controls" Namespace="Internal.Web.Controls.ScriptResourceProvider" TagPrefix="Internal" %>
<%# Register Assembly="Internal.Trial" Namespace="Internal.Trial" TagPrefix="InternalTrial" %>
<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="ContentPlaceHolderArea">
<script type="text/javascript">
</script>
<asp:Label ID="lblTest" runat="server"></asp:Label>
<asp:Login ID="intLogin" runat="server" DestinationPageUrl="Default.aspx"
OnPreRender="PreRender" Font-Names="Arial,Verdana,Sans-sarif" Font-Size="0.8em"
ForeColor="#000000">
<LayoutTemplate>
<div id="logoContainer">
<div class="logo"><img src="images/icons/logo.png" width="680" height="100"></div>
</div>
<div id="logonContainer">
<div>
<div class="LoginBtn1" onclick="lgnUser('pam')">Admin - Pam</div>
<div class="User1"><img src="images/icons/user1.png" width="80" height="80"></div>
<div class="LoginBtn2" onclick="lgnUser('lee')">Sales - Lee</div>
<div class="User2"><img src="images/icons/user2.png" width="80" height="80"></div>
</div>
<div>
<div class="LoginBtn1" onclick="lgnUser('samantha')">Support - Samantha</div>
<div class="User1"><img src="images/icons/user3.png" width="80" height="80"></div>
<div class="LoginBtn2" onclick="lgnUser('larry')">Marketing - Larry</div>
<div class="User2"><img src="images/icons/user4.png" width="80" height="80"></div>
</div>
</div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Label runat="server" ID="lblTest"></asp:Label>
<asp:CustomValidator ID="CustomValidator1" ControlToValidate="TextBox1"
OnServerValidate="ValidateEmail" ValidationGroup="ValidateGp"
ErrorMessage="This is a custom error validator" runat="server"/>
<asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="ValidateGp"/>
<%-- These are hidden controls used for the login process --%>
<asp:TextBox ID="UserName" runat="server" style="display: none;"></asp:TextBox>
<asp:CustomValidator ID="UserNameRequired" ValidateEmptyText="True" OnServerValidate="ValidateUserName"
ClientValidationFunction="" runat="server" ControlToValidate="UserName" ErrorMessage="<%$ resources: UserNameRequired %>"
ToolTip="<%$ resources: UserNameRequired %>" ValidationGroup="intLogin" Text="<%$ resources: asterisk %>"></asp:CustomValidator>
<asp:TextBox ID="Password" runat="server" TextMode="Password" style="display: none;"></asp:TextBox>
<asp:Button ID="btnLogin" runat="server" CommandName="Login" style="display: none;" ValidationGroup="intLogin" />
<asp:Literal ID="FailureText" runat="server" EnableViewState="False"></asp:Literal>
</LayoutTemplate>
</asp:Login>
</asp:Content>
<script type="text/C#" runat="server">
private const string AuthError = "AuthError";
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
EnsureChildControls();
}
protected new void PreRender(object sender, EventArgs e)
{
object msg = Internal.Platform.Application.ApplicationContext.Current.State[AuthError];
if (msg == null)
{
var pageId = Internal.Platform.Application.ApplicationContext.Current.State["CurrentPageID"];
var key = pageId + ":" + AuthError;
msg = Internal.Platform.Application.ApplicationContext.Current.State[key];
}
if (msg != null)
{
Internal.Platform.Application.ApplicationContext.Current.State.Remove(AuthError);
Literal FailureText = (Literal)intLogin.FindControl("FailureText");
FailureText.Text = msg.ToString();
}
}
private static void SetAuthError(string errorMsg)
{
if (!string.IsNullOrEmpty(errorMsg))
{
Internal.Platform.Application.ApplicationContext.Current.State[AuthError] = errorMsg;
}
else
{
Internal.Platform.Application.ApplicationContext.Current.State.Remove(AuthError);
}
}
protected void ValidateUserName(object source, ServerValidateEventArgs args)
{
var oValidator = (CustomValidator)source;
if (oValidator == null)
{
args.IsValid = false;
SetAuthError(GetLocalResourceObject("InvalidUserNameValidation").ToString());
return;
}
char cBadChar;
BusinessRuleHelper.InvalidUserNameReason reason;
if (BusinessRuleHelper.IsValidUserNameValue(args.Value, out reason, out cBadChar))
{
args.IsValid = true;
SetAuthError(null);
}
else
{
args.IsValid = false;
switch (reason)
{
case BusinessRuleHelper.InvalidUserNameReason.NullOrEmpty:
case BusinessRuleHelper.InvalidUserNameReason.WhiteSpace:
oValidator.ErrorMessage = GetLocalResourceObject("UserNameRequired").ToString();
break;
default:
oValidator.ErrorMessage = GetLocalResourceObject("intLoginResource1.FailureText").ToString();
break;
}
SetAuthError(oValidator.ErrorMessage);
}
}
protected void ValidateEmail(object source, ServerValidateEventArgs args)
{
if (Internal.Trial.TrialLogin.VerifyEmail(args.Value.ToString()))
{
System.Web.UI.WebControls.Label lblTest = FindControl("lblTest") as System.Web.UI.WebControls.Label;
lblTest.Text = "Test";
args.IsValid = true;
}
}
protected void Page_Error(Object sender, EventArgs e)
{
var userName = (TextBox)intLogin.Controls[0].FindControl("UserName");
string usrnm = userName.Text;
Exception err = Server.GetLastError();
if (err is Internal.Platform.Application.ValidationException)
{
string errMsg = err.Message;
}
}
</script>
Here is the login.master code:
<%# Master Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<script runat="server">
public void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
Internal.Platform.TimeZones tzs = new Internal.Platform.TimeZones();
Internal.Platform.TimeZone tz = tzs.CurrentTimeZone;
if (Request.Params["tz_info"] != null)
{
string[] tzinfo = Request.Params["tz_info"].Split(',');
if (tzinfo.Length == 11)
{
tz = tzs.FindTimeZone(tzinfo[0], tzinfo[1], tzinfo[2], tzinfo[3], tzinfo[4], tzinfo[5], tzinfo[6], tzinfo[7], tzinfo[8], tzinfo[9], tzinfo[10]);
}
}
else
{
log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
log.Warn("TimeZone: Unable to get timezone from client, using server timezone.");
}
Internal.Platform.Application.IContextService context = Internal.Platform.Application.ApplicationContext.Current.Services.Get<Internal.Platform.Application.IContextService>(true);
context.SetContext("TimeZone", tz);
}
Page.Title = GetLocalResourceObject("LoginPageTitle").ToString();
}
</script>
<script type="text/javascript">
function internalCleanUrl(strUrl) {
if(window.location.href.indexOf("internalclient") > -1) {
strUrl = strUrl;
} else {
strUrl = "internalClient" + "/" + strUrl;
}
return strUrl;
};
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head2" runat="server">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Saleslogix</title>
<link type="text/css" href="../css/internalBase.css" rel="stylesheet" />
<link type="text/css" href="../css/BDLogin.css" rel="stylesheet" />
<style type="text/css">
body {
background-color : #f1f1f1;
background-image: none;
}
</style>
<script pin="pin" type="text/javascript">
var dojoConfig = {
parseOnLoad: true,
async: true,
isDebug: false,
locale: '<%= Global.Locale %>',
paths: { 'Internal.: '../../../jscript/Internal. },
deferredOnError: function (e) {
if (dojo.config.isDebug) {
}
}
};
</script>
<script pin="pin" type="text/javascript" src="javascript:internalCleanUrl("Libraries/dojo/dojo/dojo.js">)"</script>
</head>
<body>
<script pin="pin" src="Libraries/jQuery/jquery.js" type="text/javascript"></script>
<script pin="pin" src="jscript/BDLogin.js" type="text/javascript"></script>
<script pin="pin" src="jscript/timezone.js" type="text/javascript"></script>
<script pin="pin" src="jscript/Internal.platform/gears_init.js" type="text/javascript"></script>
<form id="Form1" runat="server" method="post" >
<div class="LoginArea" id="LoginContainer">
<asp:ContentPlaceHolder ID="ContentPlaceHolderArea" runat="server"></asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
If you have a login.designer.cs file try to regenerate it (delete and then click on project and chose 'convert to web application').
Try this:
<%# Page Language="C#" AutoEventWireup="true" %>
<%# Import Namespace="System" %>
<%# Import Namespace="System.Web" %>
<%# Import Namespace="System.Web.UI" %>
<%# Import Namespace="System.Web.UI.WebControls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/C#" runat="server">
protected void btnTest_Click(object sender, EventArgs e)
{
System.Web.UI.WebControls.Label lblTest = FindControl("lblTest") as System.Web.UI.WebControls.Label;
lblTest.Text = "Test";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label runat="server" ID="lblTest"></asp:Label>
<asp:Button runat="server" ID="btnTest" OnClick="btnTest_Click" Text="test" />
</div>
</form>
</body>
</html>

Verifying that a multidimensional array contains a pair of values

I am making a signin form for a webpage. I have created a multidimensional array with acceptable username/password combinations. I would like to allow the user to move on to the next page only if their username/password combination is found in the array. If they enter a combination that is not found in the array, I want an error to raise and keep them from proceeding to the next page.
I understand that this is not the most effective way to complete this command, but I am learning how to properly use Arrays as part of the foundation to my programming knowledge. I'll paste my code below. I've tried various way to get the page to do what I want, but I can't seem to get it. I get this error: "System.IndexOutOfRangeException: Index was outside the bounds of the array." Here is my code:
<%# Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
string[,] UserPass = new string[,] {{"user1","pwd1"}, {"user2", "pwd2"}, {"user3","pwd3"}};
void Page_Load(object sender, EventArgs e)
{
}
void btnSignin_Click(object sender, EventArgs e)
{
if(txtSignin.Text == UserPass[1,0] && txtPWD.Text == UserPass[0,1])
{
Response.Redirect("welcome.aspx");
}
else if (txtSignin.Text == UserPass[2, 0] && txtPWD.Text == UserPass[0, 2])
{
Response.Redirect("welcome.aspx");
}
else if (txtSignin.Text == UserPass[3, 0] && txtPWD.Text == UserPass[0, 3])
{
Response.Redirect("welcome.aspx");
}
else
{
Response.Write("Please try again.");
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link rel="stylesheet" type="text/css" href="stylesheet.css" />
</head>
<body>
<form id="form1" runat="server">
<div>
<p>Sign in with Account</p>
<asp:Panel ID="Pnl1" runat="server">
<br />
<asp:Textbox ID="txtSignin" runat="server" Text="Username" style="width:190px" /><br />
<asp:TextBox ID="txtPWD" runat="server" Text="Password" TextMode="Password" style="width:190px" /><br />
<asp:LinkButton ID="btnSignin" runat="server" Text="Sign in" class="myBtn" OnClick="btnSignin_Click"/><br />
<asp:CheckBox ID="chkRemember" runat="server" Text="Stay signed in" />
</asp:Panel>
<asp:Label ID="lblSignin" runat="server" />
</div>
</form>
</body>
</html>
(also, on a smaller note, is it possible to have the signin/password boxes display text that disappears when the users clicks the textbox?)
Thank you for any help!
There are different options. One is using arrays with a for loop and another is using Linq. I will show you how to do it with arrays.
string[,] UserPass = new string[,] {{"user1","pwd1"}, {"user2.edu", "pwd2"}, {"user3","pwd3"}};
...
bool isFound = false;
for (int i=0; i< UserPass.GetLength(0); i++)
{
//search users row by row
if (UserPass[i, 0] == yourSearchUserid && UserPass[i, 1] == yourSearchPassword)
{
isFound = true;
break;
}
}
//isFound holds the search result.

How to get return value (value type is Ext.Net.Panel) from DirectMethod in javascript and add it to a Ext.Net.TabPanel?

Ext.net v2.2
.Net Framework v4.5
My Direct Method
[DirectMethod]
public static Panel AddTab(int postId)
{
var pnlEditPost = new Panel
{
ID = postId.ToString(),
Icon = Icon.BookEdit,
Title = "Edit",
Layout = "Fit",
Closable = true,
AutoDoLayout = true
};
return pnlEditPost;
}
I need get the pnlEditPost in javascript and add it to my TabPanel
The exact answer is no way to return a Panel instance.
But you can return a string with a Panel's config.
<%# Page Language="C#" %>
<%# Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %>
<script runat="server">
[DirectMethod]
public static string AddTab(int count)
{
return ComponentLoader.ToConfig(new Ext.Net.Panel
{
Title = "Tab " + count,
Html = "Server time: " + DateTime.Now.ToLongTimeString()
});
}
</script>
<!DOCTYPE html>
<html>
<head runat="server">
<title>Ext.NET v2 Example</title>
<script>
var addTab = function () {
var tabPanel = App.TabPanel1;
App.direct.AddTab(tabPanel.items.getCount(), {
success: function (result) {
var tabs = tabPanel.add(eval(result));
tabPanel.setActiveTab(tabs[0]);
}
});
};
</script>
</head>
<body>
<form runat="server">
<ext:ResourceManager runat="server" />
<ext:Button runat="server" Text="Add tab" Handler="addTab" />
<ext:TabPanel ID="TabPanel1" runat="server" />
</form>
</body>
</html>
Also you might be interested to look at this example.

Show another image onmouseover in javascript

I am having a problem with my javascript in Visual Studio. What I want to do is when i hover over the region of the country, like on this site www.pazar3.mk, a new image from that region should appear (which is transparent) with new color. I am going to post the code that I have. It doesn't return errors, but it doesn't work either. It just takes me to another .aspx site when I click on the region and it doesn't show the other image with the new color. Here's the code that I have, so please, can you tell me what I'm missing or should I change something with my code?
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
width: 530px;
height: 380px;
z-index: 1;
left: 10px;
top: 399px;
position: absolute;
}
.auto-style2 {
width: 530px;
height: 380px;
}
</style>
<script type="text/javascript">
function newImage(arg) {
if (document.images) {
rslt = new Image();
rslt.src = arg;
return rslt;
}
}
function changeImages() {
if (document.images && (preloadFlag == true)) {
for (var i = 0; i < changeImages.arguments.length; i += 2) {
document[changeImages.arguments[i]].src = changeImages.arguments[i + 1];
}
}
}
var preloadFlag = false;
function preloadImages() {
if (document.images) {
img1 = newImage("Sliki/1.gif");
img2 = newImage("Sliki/2.gif");
img12 = newImage("Sliki/12.gif");
img23 = newImage("Sliki/23.gif");
preloadFlag = true;
}
}
</script>
</head>
<body onload="preloadImages();" >
<form id="form1" runat="server">
<div style="height: 386px; width: 906px">
<img src="Sliki/map (1).jpg" width="530" height="380" id="map"
usemap="#m_map" alt="" /><map name="m_map" id="m_map">
<area shape="poly" coords="167,335,168,321,166,318,161,313,156,308,148,308,146,304,143,302,137,301,136,293,133,283,130,277,127,273,127,270,129,266,133,261,133,253,132,248,128,242,124,240,121,240,118,243,114,248,108,254,100,258,94,261,92,261,91,268,87,274,83,279,81,281,81,286,81,291,81,295,75,298,69,304,67,308,66,316,69,318,79,319,86,319,88,321,91,324,94,326,100,325,102,322,103,317,100,315,95,314,88,312,85,308,87,303,90,300,94,297,98,294,104,293,109,293,113,295,119,303,124,311,127,318,130,327,131,335,132,338,135,336,140,332,144,331,148,331,151,333,155,336,162,336,167,335"
href="Default2.aspx" title="Resen" alt="Resen" onmouseover="changeImages('map', 'Sliki/23.gif'); return true;"
onmouseout="changeImages('map', 'Sliki/map(1).jpg'); return true;" onmousedown="changeImages('map', 'Sliki/23.gif'); return true;"
onmouseup="changeImages('map', 'Sliki/23.gif'); return true;" />
</map>
</div>
</form>

asp.net multiple uploads with multiple fileupload control

I'm working in tiny project that deal with multiple file uploading.
at the begining user have one fileupload control and a small image called fileuploadadder .
each time user click on fileuploadadder , a clone of the first fileupload control added to the page with jquery . the ids of the fileupload controls are uniqe. such as file1 , file2, ...
now , i want when user clicks on a button at the end of the page asp.net uploads the selected files.
tnx
Here's an example:
<%# Page Language="C#" %>
<%# Import Namespace="System.IO" %>
<script type="text/c#" runat="server">
protected void BtnUpload_Click(object sender, EventArgs e)
{
if (Request.Files != null)
{
foreach (string file in Request.Files)
{
var uploadedFile = Request.Files[file];
if (uploadedFile.ContentLength > 0)
{
var appData = Server.MapPath("~/app_data");
var fileName = Path.GetFileName(uploadedFile.FileName);
uploadedFile.SaveAs(Path.Combine(appData, fileName));
}
}
}
}
</script>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form id="Form1" runat="server" enctype="multipart/form-data">
Add file
<div id="files"></div>
<asp:LinkButton ID="BtnUpload" runat="server" Text="Upload" OnClick="BtnUpload_Click" />
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$('#add').click(function () {
$('#files').append($('<input/>', {
type: 'file',
name: 'file' + new Date().getTime()
}));
return false;
});
</script>
</body>
</html>

Categories