为什么我的应用程序告诉我我的剪贴板是空的,但显然不是?
Why is my application telling me that my clipboard is empty when clearly it's not?
我正在尝试使用控制台应用程序截取我的屏幕截图,然后将其保存到我的桌面,但出于某种原因......它告诉我我的剪贴板是空的,但显然不是......如果你检查代码你可以看到我按下了 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 说:
The Clipboard class can only be used in threads set to single thread apartment (STA) mode. To use this class, ensure that your Main method is marked with the STAThreadAttribute attribute.
我正在尝试使用控制台应用程序截取我的屏幕截图,然后将其保存到我的桌面,但出于某种原因......它告诉我我的剪贴板是空的,但显然不是......如果你检查代码你可以看到我按下了 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 说:
The Clipboard class can only be used in threads set to single thread apartment (STA) mode. To use this class, ensure that your Main method is marked with the STAThreadAttribute attribute.