C# 应用程序无法捕获屏幕截图
我有一个奇怪的问题,我一直在努力确定了一段时间。本质上,我的应用程序使用chrome(数组中的数据)打开各种URL,拍摄它们的照片,保存它们,然后继续在数组中循环。应用程序成功启动并运行,但可能会失败(通常在2-5天之间)。当它失败时,chrome不再显示为打开,但应用程序继续“运行”。以下是我的try/catch产生的错误: 在System.Drawing.Graphics.CopyFromScreen(Int32 sourceX、Int32 sourceY、Int32 destinationX、Int32 destinationY、Size blockRegionSize、CopyPixelOperation CopyPixelOperation) 在命令\u中心\u屏幕\u捕获\u代理.Form1.Capture(字符串名称) 我目前唯一的工作原理是,内存可能有问题,因为它无法拍摄照片,无法打开浏览器,但我不确定如何测试这个理论 {UPDATE}通过查看我所有服务器上的日志,我注意到,虽然只有一些服务器存在上述错误,但所有服务器都存在以下错误: 在System.Drawing.Image.Save(字符串文件名、ImageCodeInfo编码器、EncoderParameters encoderParams) 位于System.Drawing.Image.Save(字符串文件名,图像格式) 在服务器编辑的\Visual Studio 2012\Projects\Command Center Screen Capture Agent\Command Center Screen Capture Agent\Form1.Capture(字符串名称)中的Command\u Center Screen Capture\Agent.Form1.cs:第170行 此错误似乎总是系统停止日志记录并(理论上)失败之前的最后一个错误 有关守则是:C# 应用程序无法捕获屏幕截图,c#,visual-studio-2012,screenshot,C#,Visual Studio 2012,Screenshot,我有一个奇怪的问题,我一直在努力确定了一段时间。本质上,我的应用程序使用chrome(数组中的数据)打开各种URL,拍摄它们的照片,保存它们,然后继续在数组中循环。应用程序成功启动并运行,但可能会失败(通常在2-5天之间)。当它失败时,chrome不再显示为打开,但应用程序继续“运行”。以下是我的try/catch产生的错误: 在System.Drawing.Graphics.CopyFromScreen(Int32 sourceX、Int32 sourceY、Int32 destination
try
{
GFX.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
0,
0,
Screen.PrimaryScreen.Bounds.Size,
CopyPixelOperation.SourceCopy);
}
catch (Exception e)
{
//Noticed without this if the program was running before skyvision was opened an occasional error popped up
error_logging(e.StackTrace);
}
// Save the screenshot to the specified path
try
{
String filePath = @"\" + pictureNames[count] + ".png";
// MessageBox.Show("Saving file to: " + FILEPATH_LOCATION + forTesting);
BIT.Save(@FILEPATH_LOCATION + @filePath, ImageFormat.Png);
System.Threading.Thread.Sleep(2000);
count++;
_capture.Enabled = true;
}
catch (Exception e)
{
error_logging(e.StackTrace);
//Save error without breaking in case issue with path
//MessageBox.Show("CAPTURE ERROR: \n\n" + e.StackTrace);
}
完整的源代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Drawing.Imaging;
using System.Diagnostics;
using System.IO;
using System.Configuration;
namespace Command_Center_Screen_Capture_Agent
{
public partial class Form1 : MaterialSkin.Controls.MaterialForm
{
public Form1()
{
InitializeComponent();
}
//Array storage for URLs and pic names
public static String[] URLS;
public static String[] pictureNames; //Used to save picture by name
//Data
static List<String> URL_LIST = new List<String>();
static List<String> URL_DESC = new List<String>();
static String base_url_1 = "URL_OMITTED";
static String base_url_2 = "URL_OMITTED";
static Configuration configManager = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
int count = 0;
//Create a new bitmap.
static Image BIT = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height,
PixelFormat.Format32bppArgb);
// Create a graphics object from the bitmap.
Graphics GFX = Graphics.FromImage(BIT);
string FILEPATH_LOCATION = (@"FILEPATH_OMITTED");
string ERROR_LOGGING = Path.Combine(Application.StartupPath, "Error Logs");
private void error_logging(string line)
{
try
{
Guid filename = Guid.NewGuid();
string targetPath = Path.Combine(ERROR_LOGGING, filename + ".txt");
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(targetPath))
{
file.WriteLine(line);
}
}
catch (Exception E)
{
MessageBox.Show("Failure Writing Error log. " + E.StackTrace);
}
}
private void load_data()
{
//Attempt to load data
try
{
string line;
System.IO.StreamReader file =
new System.IO.StreamReader(AppDomain.CurrentDomain.BaseDirectory + "data.txt");
while ((line = file.ReadLine()) != null)
{
if (line.Contains("SERVERS:"))
{
URL_LIST = line.Substring(8).Split(',').ToList();
}
if (line.Contains("DESC:"))
{
URL_DESC = line.Substring(5).Split(',').ToList();
}
}
file.Close();
}
catch (Exception criticalError)
{
MessageBox.Show("Critical Error. Could not access data file. Closing application. \n\n" + criticalError.StackTrace);
Application.Exit();
}
}
private void build_error_log()
{
if (!Directory.Exists(ERROR_LOGGING))
{
Directory.CreateDirectory(ERROR_LOGGING);
}
}
private void Form1_Load(object sender, EventArgs e)
{
build_error_log();
load_data();
Checkpath();
cycleTimeTxtBx.Text = Properties.Settings.Default.TimeToLoadPage.ToString();
}
private bool Checkpath()
{
this.Hide();
if (Directory.Exists(FILEPATH_LOCATION))
{
return (true);
}
else
{
DirectoryInfo dir = Directory.CreateDirectory(FILEPATH_LOCATION);
return false;
}
}
private void Capture(string name)
{
try
{
if (!Checkpath())
{
System.Threading.Thread.Sleep(1000);
}
}
catch (Exception whoops)
{
error_logging(whoops.StackTrace);
//Console.WriteLine(whoops);
}
// Take the screenshot from the upper left corner to the right bottom corner.
try
{
GFX.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
0,
0,
Screen.PrimaryScreen.Bounds.Size,
CopyPixelOperation.SourceCopy);
}
catch (Exception e)
{
error_logging(e.StackTrace);
}
// Save the screenshot to the specified path
try
{
String filePath = @"\" + pictureNames[count] + ".png";
BIT.Save(@FILEPATH_LOCATION + @filePath, ImageFormat.Png);
System.Threading.Thread.Sleep(2000);
count++;
_capture.Enabled = true;
}
catch (Exception e)
{
error_logging(e.StackTrace);
//Save error without breaking in case issue with path
//MessageBox.Show("CAPTURE ERROR: \n\n" + e.StackTrace);
}
KillChrome();
}
private void KillChrome()
{
try
{
Process[] procsChrome = Process.GetProcessesByName("chrome");
foreach (Process pro in procsChrome)
{
pro.Kill();
}
}
catch (Exception e)
{
error_logging(e.StackTrace);
Console.WriteLine(e);
}
}
private void _capture_Tick(object sender, EventArgs e)
{
//Assume that the URL array hasn't been setup
if (URLS == null || URLS.Length < 1)
{
URLS = URL_LIST.ToArray();
pictureNames = URL_DESC.ToArray();
}
try
{
Process process = new Process();
process.StartInfo.FileName = "chrome.exe";
if (count < URLS.Length)
{
string sysCode = URLS[count];
string market;
int delimIndex = sysCode.IndexOf("|");
market = sysCode.Substring(delimIndex + 1);
sysCode = sysCode.Substring(0, delimIndex);
string useable_url = base_url_1 + sysCode + base_url_2 + market;
process.StartInfo.Arguments = useable_url + " --start-maximized --incognito --new-window";
}
else
{
count = 0;
string sysCode = URLS[count];
string market;
int delimIndex = sysCode.IndexOf("|");
market = sysCode.Substring(delimIndex + 1);
sysCode = sysCode.Substring(0, delimIndex);
string useable_url = base_url_1 + sysCode + base_url_2 + market;
process.StartInfo.Arguments = useable_url + " --start-maximized --incognito --new-window";
}
process.Start();
_capture.Enabled = false;
System.Threading.Thread.Sleep(Properties.Settings.Default.TimeToLoadPage * 1000);
Capture("no");
}
catch (Exception error)
{
error_logging(error.StackTrace);
//MessageBox.Show(error.StackTrace);
}
}
private void startBTN_Click(object sender, EventArgs e)
{
_capture.Enabled = true;
this.Hide();
notifyIcon1.Visible = true;
}
private void saveBtn_Click(object sender, EventArgs e)
{
try
{
Properties.Settings.Default.TimeToLoadPage = Convert.ToInt32(cycleTimeTxtBx.Text);
Properties.Settings.Default.Save();
}
catch (Exception error)
{
MessageBox.Show("Error: Unable to parse cycle timer. Please only use integers when setting the cycle time.", "Parsing Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
cycleTimeTxtBx.Text = Properties.Settings.Default.TimeToLoadPage.ToString();
}
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
Console.WriteLine("Clicked");
Show();
_capture.Enabled = false;
this.WindowState = FormWindowState.Normal;
notifyIcon1.Visible = false;
}
}
}
使用系统;
使用System.Collections.Generic;
使用系统组件模型;
使用系统数据;
使用系统图;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用System.Windows.Forms;
使用System.Runtime.InteropServices;
使用系统、绘图、成像;
使用系统诊断;
使用System.IO;
使用系统配置;
名称空间命令\u中心\u屏幕\u捕获\u代理
{
公共部分类表单1:MaterialSkin.Controls.MaterialForm
{
公共表格1()
{
初始化组件();
}
//URL和pic名称的数组存储
公共静态字符串[]URL;
公共静态字符串[]pictureNames;//用于按名称保存图片
//资料
静态列表URL_List=新列表();
静态列表URL_DESC=新列表();
静态字符串base\u url\u 1=“url\u省略”;
静态字符串base\u url\u 2=“url\u省略”;
静态配置configManager=ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
整数计数=0;
//创建一个新位图。
静态图像位=新位图(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height,
PixelFormat.Format32bppArgb);
//从位图创建图形对象。
Graphics GFX=Graphics.FromImage(位);
字符串FILEPATH_LOCATION=(@“FILEPATH_省略”);
字符串ERROR_LOGGING=Path.Combine(Application.StartupPath,“错误日志”);
私有无效错误\u日志记录(字符串行)
{
尝试
{
Guid文件名=Guid.NewGuid();
字符串targetPath=Path.Combine(错误记录,文件名+“.txt”);
使用(System.IO.StreamWriter)文件=
新系统IO.StreamWriter(目标路径))
{
文件写入线(第行);
}
}
捕获(例外E)
{
MessageBox.Show(“写入错误日志失败”。+E.StackTrace);
}
}
私有无效加载_数据()
{
//尝试加载数据
尝试
{
弦线;
System.IO.StreamReader文件=
新System.IO.StreamReader(AppDomain.CurrentDomain.BaseDirectory+“data.txt”);
而((line=file.ReadLine())!=null)
{
if(第行包含(“服务器:”)
{
URL_LIST=line.Substring(8).Split(',').ToList();
}
如果(第行包含(“说明:”)
{
URL_DESC=line.Substring(5).Split(',').ToList();
}
}
file.Close();
}
捕获(异常关键错误)
{
MessageBox.Show(“严重错误。无法访问数据文件。正在关闭应用程序。\n\n”+criticalError.StackTrace);
Application.Exit();
}
}
私有无效生成错误日志()
{
如果(!Directory.Exists(错误_日志记录))
{
CreateDirectory(错误记录);
}
}
私有void Form1\u加载(对象发送方、事件参数e)
{
生成错误日志();
加载_数据();
检查路径();
cycleTimeTxtBx.Text=Properties.Settings.Default.TimeToLoadPage.ToString();
}
私有布尔校验路径()
{
this.Hide();
if(Directory.Exists(FILEPATH\u位置))
{
返回(真);
}
其他的
{
DirectoryInfo dir=Directory.CreateDirectory(文件路径\位置);
返回false;
}
}
私有无效捕获(字符串名称)
{
尝试
{
如果(!Checkpath())
{
系统线程线程睡眠(1000);
}
}
捕捉(异常叫声)
{
错误日志记录(哎哟.StackTrace);
//控制台。WriteLine(谁