我试图用控制台应用程序截取屏幕截图,然后将其保存到桌面,但是出于某种原因。它告诉我剪贴板显然是空的,如果不是,则为空。如果检查代码,您会看到我按PrintScreen,然后将其保存到剪贴板。
using System;
using System.Drawing;
using System.Windows.Forms;
namespace ScreenshotConsole
{
class Program
{
static void Main(string[] args)
{
screenshot();
Console.WriteLine("Printescreened");
saveScreenshot();
Console.ReadLine();
}
static void screenshot()
{
SendKeys.SendWait("{PRTSC}");
}
static void saveScreenshot()
{
//string path;
//path = "%AppData%\\Sys32.png"; // collection of paths
//path = Environment.ExpandEnvironmentVariables(path);
if (Clipboard.ContainsImage() == true)
{
Image image = (Image)Clipboard.GetDataObject().GetData(DataFormats.Bitmap);
image.Save("image.jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
}
else
{
Console.WriteLine("Clipboard empty.");
}
}
}
}
截屏需要一些时间,因此您应该在按{PRTSC}
以下键后添加延迟:
static void screenshot()
{
SendKeys.SendWait("{PRTSC}");
Thread.Sleep(500);
}
好的,我想通了,将其添加STAThreadAttribute
到您的主要方法中:
[STAThread]
static void Main(string[] args)
{
screenshot();
Console.WriteLine("Printescreened");
saveScreenshot();
Console.ReadLine();
}
MSDN说:
Clipboard类只能在设置为单线程单元(STA)模式的线程中使用。要使用此类,请确保您的Main方法已标记为STAThreadAttribute属性。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句