[英]How to run console app in background [C#]
I want to run this code in a background (no console showing up), so I changed the output type to Windows Application but then the program doesn't work. 我想在后台运行此代码(不显示任何控制台),因此我将输出类型更改为Windows应用程序,但是该程序无法正常工作。
When I change the output back to Console Application , then everything works, but it is not running in the background... If you know any better solution, or you know an already written software which does the same thing please comment it here :) 当我将输出更改回Console Application时 ,一切正常,但它并未在后台运行...如果您知道任何更好的解决方案,或者您已经编写了可以执行相同操作的软件,请在此处进行评论:)
The code is basically copying text to clipboard from a resource when a key is pressed. 该代码基本上是在按下键时将文本从资源复制到剪贴板。
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;
}
}
}
}
}
So my way to fix your problem is not necessarily to run the process in the background. 因此,我解决问题的方法不必一定在后台运行该过程。 is a just different approach for the solution. 是解决方案的另一种方法。
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;
}
}
}
}
}
}
And here is the link for the Keys list: https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.keys?redirectedfrom=MSDN&view=netframework-4.7.2 So think about the solution in this way: our OS is always checking if we pressed keys so why not use it? 这是“密钥”列表的链接: https : //docs.microsoft.com/zh-cn/dotnet/api/system.windows.forms.keys?redirectedfrom= MSDN &view=netframework-4.7.2因此,请考虑解决方案通过这种方式:我们的操作系统始终在检查是否按了键,为什么不使用它呢? this "user32.dll" is Our OS User Interface. 此“ user32.dll”是我们的操作系统用户界面。 so we just interface to this exist UI. 因此,我们只是连接到这个现有的UI。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.