我试图通过一小段代码从剪贴板中获取信息。我做了很多搜索,但没有一个帖子解决了我的问题。我确保我使用的是System.Windows.Forms; 下面是代码。我错过了别的什么吗?
// Rextester.Program.Main是代码的入口点。不要改变它。 //适用于Microsoft(R).NET Framework 4.5的编译器版本4.0.30319.17929
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
Clipboard.SetText(txtCopy.Text);
txtPaste.Text = Clipboard.GetText();
}
}
}
以下是运行代码时的错误
Error(s):
(22:13) The name 'Clipboard' does not exist in the current context
(22:31) The name 'txtCopy' does not exist in the current context
(23:13) The name 'txtPaste' does not exist in the current context
(23:29) The name 'Clipboard' does not exist in the current context
答案 0 :(得分:0)
您已经更改了Windows窗体应用程序的Program.main()方法,并且您没有从中启动任何窗体。在该方法中应该有这样的东西。
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
这是运行程序时调用的方法,并且没有初始化任何表单。
答案 1 :(得分:0)
您需要在文件开头引用System.Windows.Forms
才能解决剪贴板丢失错误。如果你想看,它的MSDN页面是here。
您也永远不会定义txtCopy
和txtPaste
变量,因此这些变量也会显示为缺少参考。
我假设txtCopy
和txtPaste
是表单中的某种输入?如果这是演员表你没有初始化表单,因为你从来没有创建表单,所以不会生成任何内容。即使您添加了初始化,您仍然无法访问main方法中的控件,因为对象将超出范围,因为它们包含在Form类本身中。
假设您使用的是VS基本模板,您应该按如下方式构建代码以实现您的功能。
的Program.cs:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
Form1.cs的
public Form1()
{
InitializeComponent();
/* Once you call the InitializeComnents method you will be able to access controls added in design view */
Clipboard.SetText(txtCopy.Text);
txtPaste.Text = Clipboard.GetText();
}
也记住你的使用陈述!