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.
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 :)
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://learn.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? this "user32.dll" is Our OS User Interface. so we just interface to this exist UI.