如何在后台运行控制台应用 [C#]



我想在后台运行此代码(没有显示控制台(,所以我将输出类型更改为Windows应用程序,但随后程序不起作用。

当我将输出更改回控制台应用程序时,一切正常,但它不在后台运行......如果您知道任何更好的解决方案,或者您知道已经编写的软件可以做同样的事情,请在此处发表评论:)

代码基本上是在按下某个键时将文本从资源复制到剪贴板。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Resources;
using System.Reflection;
namespace EzClipBoard
{
class Program
{
[STAThreadAttribute]
static void Main(string[] args)
{
int exit = 1;
string bubblesort = codes.ResourceManager.GetString("bubblesort");
string insertion = codes.ResourceManager.GetString("insertion");
while(exit != 0)
{
if (Console.ReadKey(true).Key == ConsoleKey.X)
{
Clipboard.SetText(bubblesort);
}
else if (Console.ReadKey(true).Key == ConsoleKey.Y)
{
Clipboard.SetText(insertion);
}
else if (Console.ReadKey(true).Key == ConsoleKey.Escape)
{
exit = 0;
}
}
}
}
}

因此,我解决您的问题的方法不一定是在后台运行该过程。 只是解决方案的不同方法。

class Program
{
[DllImport("user32.dll")]
public static extern int GetAsyncKeyState(Int32 i);
static void Main(string[] args)
{
while (true)
{
Thread.Sleep(100);
for (int i = 0; i < 255; i++)
{
int keyState = GetAsyncKeyState(i);
if (keyState == 1 || keyState == -32767)
{
Console.WriteLine(i);
if (i == 88 ) // X Key
{
Console.WriteLine(i);
//Write what's gonning to happen when 'Y' pressed
break;
}
else if (i == 89) // Y Key
{
Console.WriteLine(i);
//Write what's gonning to happen when 'Y' pressed
break;
}
else if (i == 27) // Escape Key
{
Console.WriteLine(i);
//Write what's gonning to happen when 'Y' pressed
break;
}
}
}
}
}
}

这是密钥列表的链接: https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.keys?redirectedfrom=MSDN&view=netframework-4.7.2 因此,以这种方式考虑解决方案:我们的操作系统总是在检查我们是否按下了键,那么为什么不使用它呢?这个"user32.dll"是我们的操作系统用户界面。所以我们只是连接到这个存在的 UI。

相关内容

最新更新