0% found this document useful (0 votes)
2 views29 pages

changes

The document outlines the code for a C# application using Avalonia framework that simulates keyboard actions and manages window/tab switching across different operating systems. It includes features like timers for key presses, hotkey registration, and notifications, along with methods to handle different OS-specific key simulation. The application also manages user-selected intervals and keys, providing a customizable experience for automation tasks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views29 pages

changes

The document outlines the code for a C# application using Avalonia framework that simulates keyboard actions and manages window/tab switching across different operating systems. It includes features like timers for key presses, hotkey registration, and notifications, along with methods to handle different OS-specific key simulation. The application also manages user-selected intervals and keys, providing a customizable experience for automation tasks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 29

using Avalonia.

Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using System;

using MsBox.Avalonia;

using System.Collections.Generic;

using WindowsInput;
using WindowsInput.Native;
using Avalonia.Controls.Notifications;
using Avalonia.Threading;
using Avalonia.Media.Imaging;
using System.IO;

using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;
using Avalonia.Media.Immutable;
using Avalonia.Input;
using Avalonia.Remote.Protocol.Input;
using System.Linq;
using Avalonia;
using Avalonia.Markup.Xaml;
using Avalonia.Platform;

#if WINDOWS
using WindowsInput;
using WindowsInput.Native;
#endif

namespace MHZ_ATTS1
{
public partial class MainWindow : Window
{

private string SelectedKeys;


private int SelectedTime;
public HotKeyRegistryClass hotkey = new HotKeyRegistryClass();
private System.Timers.Timer singleKeyTimer;
private System.Timers.Timer combinedKeyTimer;
private System.Timers.Timer NoOfTabsTimer;
private System.Timers.Timer RandomTabsTimer;
private System.Timers.Timer ActivateTimer;
private System.Timers.Timer cursorTimer;

NotificationToast notificationToast = new NotificationToast();

private InputSimulator inputSimulator = new InputSimulator();

private const string TrialStartFile = "trial_start_date.txt";


private readonly TimeSpan trialDuration = TimeSpan.FromDays(3);
public static int getRemainingDate, getRemainingTime = 0;

// Region: KMCODE-1
// Total number of tabs/windows (will be selected by the user from combo)
private int totalTabs;

// Current tab index


private int currentTabIndex = 1;

// Timer object
private System.Timers.Timer timer = new System.Timers.Timer();

// Manual interval time (will be selected from combo)


private int intervalTime;

// Flag to indicate whether the timer is paused


private bool isPaused = false;

// Random object for shuffling tabs


private Random rnd = new Random();

// List to hold shuffled tabs


private List<int> shuffledTabs = new List<int>();

// Index for shuffled tabs


private int shuffledIndex = 0;

// Execution cycle counter


private int execCycle = 1;

// End Region

string BaseDirectory;
string projectDirectory;
string resourcesPath;
string imagePath;
string imagePath_;
string imagePath2;
string textFilePath;

public void getAllFiles()


{
BaseDirectory = AppDomain.CurrentDomain.BaseDirectory;
resourcesPath = Path.Combine(BaseDirectory, "Resources");
imagePath = Path.Combine(resourcesPath, "MHZ-ATTS Logo.png");
imagePath_ = Path.Combine(resourcesPath, "MHZ-ATTS-Logo-2.png");
imagePath2 = Path.Combine(resourcesPath, "TimeCloak Logo.png");
// textFilePath = Path.Combine(resourcesPath, "trial_start_date.txt");

#if WINDOWS
private InputSimulator inputSimulator = new InputSimulator();
#endif
public MainWindow()
{
InitializeComponent();
singleKeyTimer = new System.Timers.Timer();
combinedKeyTimer = new System.Timers.Timer();
NoOfTabsTimer = new System.Timers.Timer();
RandomTabsTimer = new System.Timers.Timer();
ActivateTimer = new System.Timers.Timer();
cursorTimer = new System.Timers.Timer();

singleKeyTimer.Enabled = false;
combinedKeyTimer.Enabled = false;
NoOfTabsTimer.Enabled = false;
RandomTabsTimer.Enabled = false;
ActivateTimer.Enabled = false;
cursorTimer = new System.Timers.Timer();

//singleKeyTimer.Elapsed += SingleKeyTimer_Elapsed;
combinedKeyTimer.Elapsed += CombinedKeyTimer_Elapsed;
NoOfTabsTimer.Elapsed += NoOfTabsTimer_Elapsed;
RandomTabsTimer.Elapsed += RandomTabsTimer_Elapsed;
ActivateTimer.Elapsed += ActivateTimer_Elapsed;
cursorTimer.Elapsed += CursorTimer_Elapsed;
}

// Function to simulate key presses


public void SimulateKeyPress(string userSelectedKey)
{
// Get the key representation
string keyToPress = FuncPressKeys(userSelectedKey);

// Use InputSimulator to simulate the key press


//
inputSimulator.Keyboard.KeyPress((VirtualKeyCode)Enum.Parse(typeof(VirtualKeyCode),
keyToPress.Replace("{", "").Replace("}", "").ToUpper()));

#if WINDOWS
// Windows - Use InputSimulator

inputSimulator.Keyboard.KeyPress((VirtualKeyCode)Enum.Parse(typeof(VirtualKeyCode),
keyToPress.Replace("_", "").ToUpper()));
#else
//Cross - platform shell - based key simulation
if (OperatingSystem.IsWindows())
{
// Use InputSimulator for windows
if (keyToPress.Equals("{SCROLLLOCK}",
StringComparison.OrdinalIgnoreCase))
{
// Simulate Scroll Lock key press
inputSimulator.Keyboard.KeyPress(VirtualKeyCode.SCROLL);
}
}
else if (OperatingSystem.IsLinux())
{
// Use xdotool for Linux
Process.Start("/bin/bash", "-c \"xdotool key " + keyToPress +
"\"");
}
else if (OperatingSystem.IsMacOS())
{
// Use AppleScript for macOS
Process.Start("/bin/bash", "-c \"osascript -e 'tell
application \\\"System Events\\\" to keystroke \"" + keyToPress + "\"'\"");
}
#endif

private void SingleKeyTimer_Elapsed(object sender,


System.Timers.ElapsedEventArgs e)
{
Dispatcher.UIThread.InvokeAsync(() =>
{
// Logic for single key timer
SimulateKeyPress(comSingleKeys.SelectedItem.ToString());
});

private void CombinedKeyTimer_Elapsed(object sender,


System.Timers.ElapsedEventArgs e)
{

Dispatcher.UIThread.InvokeAsync(() =>
{
// Logic for combined key timer

if (btnkey1.Background == Brushes.LightGreen)
{
SimulateKeyPress("Scroll Lock");
}

if (btnkey2.Background == Brushes.LightGreen)
{
SimulateKeyPress("Scroll Lock");
}

if (btnkey2.Background != Brushes.LightGreen &&


btnkey1.Background != Brushes.LightGreen)
{
combinedKeyTimer.Enabled = false;
btnKeyComStop.IsEnabled = false;
btnKeyComStart.IsEnabled = true;
comInterval.IsEnabled = false;
comFirstKey.IsEnabled = true;
}

});
}
private void MenuItem_Click(object? sender,
Avalonia.Interactivity.RoutedEventArgs e)
{
About about = new About();
about.Show();
}

private void MenuItem_Click_1(object? sender,


Avalonia.Interactivity.RoutedEventArgs e)
{
trayIcon.IsVisible = false;
Environment.Exit(0);
}

private void Window_Closing(object? sender,


Avalonia.Controls.WindowClosingEventArgs e)
{
if (!e.Cancel)
{
e.Cancel = true;
this.Hide();
notificationToast.ShowAllOSNotitcations();

}
}

private void Window_PropertyChanged(object? sender,


Avalonia.AvaloniaPropertyChangedEventArgs e)
{
if (e.Property == Window.WindowStateProperty && this.WindowState ==
WindowState.Minimized)
{
this.Hide();
this.ShowInTaskbar = false;
notificationToast.ShowAllOSNotitcations();
}
}

public List<string> keyList1 = new List<string>();


public List<string> keyList2 = new List<string>();
public List<string> keyList3 = new List<string>();
public List<string> keyList4 = new List<string>();

private void Window_Loaded_2(object? sender,


Avalonia.Interactivity.RoutedEventArgs e)
{

getAllFiles();

this.Icon = new WindowIcon(new Bitmap(imagePath_));


// this.imgtoplogo.Source = new
Bitmap(System.IO.Path.Combine(AppContext.BaseDirectory, "TimeCloak Logo.png"));

createTrayIcon();

keyList1.Clear();
keyList1.AddRange(FuncAddIntervals());
comInterval.ItemsSource = keyList1;
comSingleInterval.ItemsSource = keyList1;

keyList2.Clear();
keyList2.AddRange(FuncAddKeys());
comSingleKeys.ItemsSource = keyList2;

keyList3.Clear();
keyList3.AddRange(FuncAddTabsNo());
comTabs.ItemsSource = keyList3;

keyList4.Clear();
keyList4.AddRange(FuncAddTabsInterval());
comInterval2.ItemsSource = keyList4;

btnSingleStart.IsEnabled = false;
comSingleInterval.IsEnabled = false;
combinedKeyTimer.Enabled = false;

//NotifyIcon.Visible = true;
//NotifyIcon.ContextMenuStrip = notifi_menu;

//NotifyIcon.BalloonTipText = "Welcome~! AKP is Running";


//NotifyIcon.Icon = (Icon)My.Resources.IconNotify;
//NotifyIcon.ShowBalloonTip(5);

hotkey.Register((int)HotKeyRegistryClass.Modifiers.MOD_CTRL,
Avalonia.Input.Key.F3);
hotkey.Register((int)HotKeyRegistryClass.Modifiers.MOD_CTRL,
Avalonia.Input.Key.F4);
hotkey.Register((int)HotKeyRegistryClass.Modifiers.MOD_CTRL,
Avalonia.Input.Key.F5);
hotkey.Register((int)HotKeyRegistryClass.Modifiers.MOD_CTRL,
Avalonia.Input.Key.F6);
hotkey.Register((int)HotKeyRegistryClass.Modifiers.MOD_CTRL,
Avalonia.Input.Key.F7);
hotkey.Register((int)HotKeyRegistryClass.Modifiers.MOD_CTRL,
Avalonia.Input.Key.F8);
hotkey.Register((int)HotKeyRegistryClass.Modifiers.MOD_CTRL,
Avalonia.Input.Key.F9);

// Region: KMCODE-2
// Attach the event handler for the timer
timer.Elapsed += OnTimedEvent;

// End Region

private List<int> availableWindows;


// Region: KMCODE-3
private void OnTimedEvent(object sender, System.Timers.ElapsedEventArgs e)
{
Dispatcher.UIThread.InvokeAsync(() =>
{
if (!isPaused)
{
int targetTabIndex = 0;
if (toggletabbutton.IsChecked == true)
{
if (shuffledIndex >=
int.Parse(comTabs.SelectedItem.ToString()))
{
shuffledIndex = 0; // Reset to start from the first
screen in range
}

targetTabIndex = shuffledTabs[shuffledIndex];
shuffledIndex++;

////Get the random tab from the shuffled list


//int randomTab = shuffledTabs[shuffledIndex];

////Update the shuffled index and ensure it stays within


the selected range
//shuffledIndex = (shuffledIndex + 1) % totalTabs;
// Execute tab switch and random key presses
SwitchTabs(targetTabIndex);

}
if (togglescreenbutton.IsChecked == true)
{
// Initialize the available windows (1 to
selectedNumberOfScreens)
availableWindows = Enumerable.Range(1,
int.Parse(comTabs.SelectedItem.ToString())).ToList();

// Pick a random screen from the available range


targetTabIndex =
availableWindows[rand.Next(availableWindows.Count)];
// Execute Screen switch and random key presses
SwitchScreen(targetTabIndex-1);
}

//RandomUpDownKeyPresses();

// Update the current tab index for internal tracking/logging


currentTabIndex = targetTabIndex;
}
});
}
// End Region

int x = 0;
private void RandomUpDownKeyPresses()
{
var sim = new InputSimulator();
int upPresses = 0;
int downPresses = 0;

Random random = new Random(); // Instantiate a random number generator


int x = random.Next(0, 2); // Generate a random number (0 or 1)

if (x == 0)
{
for (int i = 0; i < 30; i++)
{
sim.Keyboard.KeyPress(VirtualKeyCode.UP);
Thread.Sleep(100); // Delay of 100ms
}
x = 1;
}
else if(x==1)
{
for (int i = 0; i < 30; i++)
{
sim.Keyboard.KeyPress(VirtualKeyCode.DOWN);
Thread.Sleep(100); // Delay of 100ms
}
x = 0;
}

private void SwitchTabs(int targetTabIndex)


{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
SwitchTabsWindows(targetTabIndex);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
SwitchTabsLinux(targetTabIndex);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
SwitchTabsMac(targetTabIndex);
}
}

private void SwitchTabsWindows(int targetTabIndex)


{
var sim = new InputSimulator();

for (int i = 1; i <= Math.Abs(currentTabIndex - targetTabIndex); i++)


{
if (targetTabIndex > currentTabIndex)
{
// Simulate Alt + Tab (forward)
sim.Keyboard.ModifiedKeyStroke(VirtualKeyCode.CONTROL,
VirtualKeyCode.TAB);
}
else
{
// Simulate Alt + Shift + Tab (backward)
sim.Keyboard.ModifiedKeyStroke(new[] { VirtualKeyCode.CONTROL,
VirtualKeyCode.SHIFT }, VirtualKeyCode.TAB);
}

Thread.Sleep(100); // Pause to allow tab switching


}

currentTabIndex = targetTabIndex;

private void SwitchTabsLinux(int targetTabIndex)


{

for (int i = 1; i <= Math.Abs(currentTabIndex - targetTabIndex); i++)


{
if (targetTabIndex > currentTabIndex)
{
// Simulate Alt + Tab (forward)
Process.Start("xdotool", "key ctrl+Tab");
}
else
{
// Simulate Alt + Shift + Tab (backward)
Process.Start("xdotool", "key ctrl+Shift+Tab");
}

Thread.Sleep(100); // Pause to allow tab switching


}

currentTabIndex = targetTabIndex;
}

private void SwitchTabsMac(int targetTabIndex)


{
for (int i = 1; i <= Math.Abs(currentTabIndex - targetTabIndex); i++)
{
if (targetTabIndex > currentTabIndex)
{
// Simulate Command + Tab (forward)
Process.Start("osascript", "-e 'tell application \"System
Events\" to key code 48 using {control down}'");
}
else
{
// Simulate Command + Shift + Tab (backward)
Process.Start("osascript", "-e 'tell application \"System
Events\" to key code 48 using {control down, shift down}'");
}

Thread.Sleep(100); // Pause to allow tab switching


}

currentTabIndex = targetTabIndex;

private void SwitchScreen(int targetTabIndex)


{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
SwitchScreenWindows(targetTabIndex);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
SwitchScreenLinux(targetTabIndex);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
SwitchScreenMac(targetTabIndex);
}
}
private void SwitchScreenWindows(int targetTabIndex)
{
var sim = new InputSimulator();

// Move to the target window in the Alt+Tab list


for (int i = 0; i < targetTabIndex; i++)
{
sim.Keyboard.KeyDown(VirtualKeyCode.MENU); // Hold Alt
sim.Keyboard.KeyPress(VirtualKeyCode.TAB); // Press Tab
Thread.Sleep(100); // Allow the system to process
}

// Release Alt to finalize the selection


sim.Keyboard.KeyUp(VirtualKeyCode.MENU);

// Update current tab index


//currentTabIndex = targetTabIndex;

private void SwitchScreenLinux(int targetTabIndex)


{
for (int i = 1; i <= Math.Abs(currentTabIndex - targetTabIndex); i++)
{
if (targetTabIndex > currentTabIndex)
{
// Simulate Alt + Tab (forward)
Process.Start("xdotool", "key Alt+Tab");
}
else
{
// Simulate Alt + Shift + Tab (backward)
Process.Start("xdotool", "key Alt+Shift+Tab");
}

Thread.Sleep(100); // Pause to allow tab switching


}

//currentTabIndex = targetTabIndex;

private void SwitchScreenMac(int targetTabIndex)


{
for (int i = 1; i <= Math.Abs(currentTabIndex - targetTabIndex); i++)
{
if (targetTabIndex > currentTabIndex)
{
// Simulate Command + Tab (forward)
Process.Start("osascript", "-e 'tell application \"System
Events\" to key code 48 using {command down}'");
}
else
{
// Simulate Command + Shift + Tab (backward)
Process.Start("osascript", "-e 'tell application \"System
Events\" to key code 48 using {command down, shift down}'");
}

Thread.Sleep(100); // Pause to allow tab switching


}

//currentTabIndex = targetTabIndex;

//protected override void WndProc()


//{
// if (m.Msg == HotKeyRegistryClass.Messages.WM_HOTKEY)
// {
// string id = m.WParam.ToString();
// switch (id)
// {
// case "0":
// if (btnSingleStart.IsEnabled) Button_Click_5(null, null);
// break;
// case "1":
// if (btnSingleStop.IsEnabled) Button_Click_3(null, null);
// break;
// case "2":
// if (btnKeyComStart.IsEnabled) Button_Click_4(null, null);
// break;
// case "3":
// if (btnKeyComStop.IsEnabled) Button_Click_8(null, null);
// break;
// case "4":
// if (btnSingleStart.IsEnabled && btnKeyComStart.IsEnabled)
// {
// Button_Click_5(null, null);
// Button_Click_4(null, null);
// }
// break;
// case "5":
// Button_Click_3(null, null);
// Button_Click_8(null, null);
// break;
// }
// }
// base.WndProc(ref m);
//}

private void Button_Click_3(object? sender,


Avalonia.Interactivity.RoutedEventArgs? e)
{
singleKeyTimer.Enabled = false;
btnSingleStart.IsEnabled = true;
comSingleKeys.IsEnabled = true;
btnSingleStop.IsEnabled = false;

private void Button_Click_4(object? sender,


Avalonia.Interactivity.RoutedEventArgs? e)
{

if (comInterval.SelectedItem == null ||
comInterval.SelectedItem.Equals("0"))
{
// Replace MessageBox with a custom dialog in Avalonia
var messageBox = MessageBoxManager.GetMessageBoxStandard("Error",
"Please select a valid interval.");
messageBox.ShowWindowDialogAsync(this);
}
else if (btnKeyComStart.Content.ToString() == "Stop" &&
(btnkey1.Background == Brushes.LightGreen || btnkey2.Background ==
Brushes.LightGreen))
{
btnKeyComStart.Content = "Start";
combinedKeyTimer.Enabled = false;
comInterval.IsEnabled = false;
btnkey1.Background = Brushes.WhiteSmoke;
btnkey2.Background = Brushes.WhiteSmoke;
btnkey1.Foreground = Brushes.SkyBlue;
btnkey2.Foreground = Brushes.SkyBlue;
comInterval.SelectedIndex = -1;
btnKeyComStart.IsEnabled = false;
btnKeyComStop.IsEnabled = false;
btnkey1.IsEnabled = true;
btnkey2.IsEnabled = true;

}
else
{
btnKeyComStart.Content = "Stop";
if(btnkey1.Background == Brushes.LightGreen && btnkey2.Background
== Brushes.LightGreen)
{
btnkey1.IsEnabled = false;
btnkey2.IsEnabled = false;
}
else
{
btnkey1.IsEnabled = false;
btnkey2.IsEnabled = false;

//if (btnkey1.Background == Brushes.LightGreen)


//{
// btnkey1.IsEnabled = false;
// btnkey2.IsEnabled = true;
//}
//if (btnkey2.Background == Brushes.LightGreen)
//{
// btnkey1.IsEnabled = true;
// btnkey2.IsEnabled = false;
//}
}

combinedKeyTimer.Interval =
FuncInterval(double.Parse(comInterval.SelectedItem.ToString()));
combinedKeyTimer.Enabled = true;
btnKeyComStop.IsEnabled = true;
comInterval.IsEnabled = false;
singleKeyTimer.Enabled = false;
btnSingleStart.IsEnabled = true;
comSingleKeys.IsEnabled = true;
btnSingleStop.IsEnabled = false;

}
}

private void ComboBox_SelectionChanged_1(object? sender,


Avalonia.Controls.SelectionChangedEventArgs e)
{
if (comSingleKeys.SelectedItem.ToString() == "-----Numbers-----" ||
comSingleKeys.SelectedItem.ToString() == "-----Alphabets-----" ||
comSingleKeys.SelectedItem.ToString() == "-----Function Keys-----"
||
comSingleKeys.SelectedItem.ToString() == "-----Special Keys-----")
{
comSingleInterval.IsEnabled = false; // Disable the interval
ComboBox
}
else
{
comSingleInterval.IsEnabled = true; // Enable the interval ComboBox
}

private void Button_Click_5(object? sender,


Avalonia.Interactivity.RoutedEventArgs? e)
{
//if (string.IsNullOrEmpty(comSingleInterval.SelectedItem.ToString()))
//{
// singleKeyTimer.Enabled = false;
//}
//else
//{
// singleKeyTimer.Interval =
FuncInterval(double.Parse(comSingleInterval.SelectedItem.ToString()));
// singleKeyTimer.Enabled = true;
// // btnSingleStop.IsEnabled = true;
// comSingleInterval.IsEnabled = false;
// comSingleKeys.IsEnabled = false;
// // btnSingleStart.IsEnabled = false;
//}
//lblKeytoPress.Focus();
}

private void ComboBox_KeyDown(object? sender, Avalonia.Input.KeyEventArgs


e)
{
if (e.Key != Avalonia.Input.Key.Back)
{
// Convert the key to character
char keyChar = (char)e.Key.ToString()[0]; // This is a simple
approach; consider key mapping for special keys.

// Check if the character is not a digit


if (keyChar < '0' || keyChar > '9')
{
e.Handled = true; // Handle the event
}
}
}

private void ComboBox_SelectionChanged(object? sender,


Avalonia.Controls.SelectionChangedEventArgs e)
{
btnKeyComStart.IsEnabled = true;
}

private void keyComFirstKey_SelectedIndexChanged(object sender, EventArgs


e)
{
// Combo box value for first key selection in key combination
if (comFirstKey.Content.ToString() == "-----Numbers-----")
{
comSecondKey.IsEnabled = false;
btnKeyComStart.IsEnabled = false;
}
else if (comFirstKey.Content.ToString() == "-----Alphabets-----")
{
comSecondKey.IsEnabled = false;
btnKeyComStart.IsEnabled = false;
}
else if (comFirstKey.Content.ToString() == "-----Function Keys-----")
{
comSecondKey.IsEnabled = false;
btnKeyComStart.IsEnabled = false;
}
else if (comFirstKey.Content.ToString() == "-----Special Keys-----")
{
comSecondKey.IsEnabled = false;
btnKeyComStart.IsEnabled = false;
}
else
{
comSecondKey.IsEnabled = true;
}
}

private void keyComSecondKey_SelectedIndexChanged(object sender, EventArgs


e)
{
// Enable comInterval only when btnKeyComStop is disabled
if (!btnKeyComStop.IsEnabled)
{
comInterval.IsEnabled = true;
}
else
{
comInterval.IsEnabled = false;
}

if (comSecondKey.Content.ToString() == "-----Numbers-----")
{
comInterval.IsEnabled = false;
btnKeyComStart.IsEnabled = false;
}
else if (comSecondKey.Content.ToString() == "-----Alphabets-----")
{
comInterval.IsEnabled = false;
btnKeyComStart.IsEnabled = false;
}
else if (comSecondKey.Content.ToString() == "-----Function Keys-----")
{
comInterval.IsEnabled = false;
btnKeyComStart.IsEnabled = false;
}
else if (comSecondKey.Content.ToString() == "-----Special Keys-----")
{
comInterval.IsEnabled = false;
btnKeyComStart.IsEnabled = false;
}
else
{
comInterval.IsEnabled = true;
}
}

// Function to convert selected time to milliseconds


public int FuncInterval(double userSelectedTime)
{
double selectedTime = userSelectedTime * 1000;
int varInterval = (int)selectedTime;
return varInterval;
}

// Function to press keys

public string FuncPressKeys(string userSelectedKey)


{
string varKey = "{" + userSelectedKey + "}";

// Lock Keys
if (userSelectedKey == "Num Lock")
varKey = "{NUMLOCK}";
else if (userSelectedKey == "Caps Lock")
varKey = "{CAPSLOCK}";
else if (userSelectedKey == "Scroll Lock")
varKey = "{SCROLLLOCK}";
else if (userSelectedKey == "TAB")
varKey = "{TAB}";
else if (userSelectedKey == "Return/Enter")
varKey = "{ENTER}";
else if (userSelectedKey == "Spacebar")
varKey = " ";
// Control, Alt, and Shift
else if (userSelectedKey == "Ctrl")
varKey = "^";
else if (userSelectedKey == "Alt")
varKey = "%";
else if (userSelectedKey == "Shift")
varKey = "+";
else if (userSelectedKey == "ESC")
varKey = "{ESC}";
// if (userSelectedKey == "Windows")
// varKey = "{WINDOWS}";
else if (userSelectedKey == "Delete")
varKey = "{DELETE}";
else if (userSelectedKey == "Backspace")
varKey = "{BKSP}";
// Arrow Keys
else if (userSelectedKey == "Down Arrow")
varKey = "{DOWN}";
else if (userSelectedKey == "Up Arrow")
varKey = "{UP}";
else if (userSelectedKey == "Left Arrow")
varKey = "{LEFT}";
else if (userSelectedKey == "Right Arrow")
varKey = "{RIGHT}";
// Home, End, Insert
else if (userSelectedKey == "Home")
varKey = "{HOME}";
else if (userSelectedKey == "End")
varKey = "{END}";
else if (userSelectedKey == "Insert")
varKey = "{INSERT}";
// Page Up and Page Down
else if (userSelectedKey == "Page Up")
varKey = "{PGUP}";
else if (userSelectedKey == "Page Down")
varKey = "{PGDN}";
else if (userSelectedKey == "Print Screen")
varKey = "{PRTSC}";

return varKey;
}

//public string FuncPressKeys(string userSelectedKey)


//{

// string varKey = "{" + userSelectedKey + "}";

// // Lock Keys
// if (userSelectedKey == "Num Lock")
// {
// varKey = "{NUMLOCK}";
// }
// else if (userSelectedKey == "Caps Lock")
// {
// varKey = "{CAPSLOCK}";
// }
// else if (userSelectedKey == "Scroll Lock")
// {
// varKey = "{SCROLLLOCK}";
// }
// else if (userSelectedKey == "TAB")
// {
// varKey = "{TAB}";
// }
// else if (userSelectedKey == "Return/Enter")
// {
// varKey = "{ENTER}";
// }
// else if (userSelectedKey == "Spacebar")
// {
// varKey = " ";
// }
// // Control, Alt and Shift
// else if (userSelectedKey == "Ctrl")
// {
// varKey = "^";
// }
// else if (userSelectedKey == "Alt")
// {
// varKey = "%";
// }
// else if (userSelectedKey == "Shift")
// {
// varKey = "+";
// }
// else if (userSelectedKey == "ESC")
// {
// varKey = "{ESC}";
// }
// else if (userSelectedKey == "Delete")
// {
// varKey = "{DELETE}";
// }
// else if (userSelectedKey == "Backspace")
// {
// varKey = "{BKSP}";
// }
// // Arrow Keys
// else if (userSelectedKey == "Down Arrow")
// {
// varKey = "{DOWN}";
// }
// else if (userSelectedKey == "Up Arrow")
// {
// varKey = "{UP}";
// }
// else if (userSelectedKey == "Left Arrow")
// {
// varKey = "{LEFT}";
// }
// else if (userSelectedKey == "Right Arrow")
// {
// varKey = "{RIGHT}";
// }
// // Home End Insert
// else if (userSelectedKey == "Home")
// {
// varKey = "{HOME}";
// }
// else if (userSelectedKey == "End")
// {
// varKey = "{END}";
// }
// else if (userSelectedKey == "Insert")
// {
// varKey = "{INSERT}";
// }
// // Page up and page down
// else if (userSelectedKey == "Page Up")
// {
// varKey = "{PGUP}";
// }
// else if (userSelectedKey == "Page Down")
// {
// varKey = "{PGDN}";
// }
// else if (userSelectedKey == "Print Screen")
// {
// varKey = "{PRTSC}";
// }
// return varKey;
//}

//// Function to add keys to a list


public string[] FuncAddKeys()
{
string[] keyList = {
"-----Numbers-----", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"-----Alphabets-----", "A", "B", "C", "D", "E", "F", "G", "H", "I",
"J",
"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X",
"Y", "Z", "-----Function Keys-----", "F1", "F2", "F3", "F4", "F5",
"F6", "F7", "F8", "F9", "F10", "F11", "F12", "-----Special Keys-----",
"NumLock", "CapsLock", "ScrollLock", "TAB", "Return/Enter", "Spacebar",
"Ctrl", "Alt", "Shift", "ESC", "Delete", "Backspace", "DownArrow",
"UpArrow", "LeftArrow", "RightArrow", "Home", "End", "Insert",
"PageUp", "PageDown", "PrintScreen"
};
return keyList;
}

// Function to add intervals to a list


public string[] FuncAddIntervals()
{
string[] intervalList = {
"0.5", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"20", "40", "60", "120", "180", "360"
};
return intervalList;
}

public string[] FuncAddTabsNo()


{
string[] keyList = {"2","3","4","5","6","7","8","9","10"
};
return keyList;
}
public string[] FuncAddTabsInterval()
{
string[] keyList = {"0.25","0.5",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10"
};
return keyList;
}
private void ComboBox_KeyDown_1(object? sender, Avalonia.Input.KeyEventArgs
e)
{
if (e.Key != Avalonia.Input.Key.Back)
{
// Convert the key to character
char keyChar = (char)e.Key.ToString()[0]; // This is a simple
approach; consider key mapping for special keys.

// Check if the character is not a digit


if (keyChar < '0' || keyChar > '9')
{
e.Handled = true; // Handle the event
}
}
}

private void ComboBox_SelectionChanged_2(object? sender,


Avalonia.Controls.SelectionChangedEventArgs e)
{
btnSingleStart.IsEnabled = true;
}

private void Button_Click_6(object? sender,


Avalonia.Interactivity.RoutedEventArgs e)
{
comInterval.IsEnabled = true;
btnKeyComStart.IsEnabled = true;

if (btnkey1.Background == Brushes.LightGreen)
{
// If the background color is green, change it to transparent
btnkey1.Background = Brushes.WhiteSmoke;
btnkey1.Foreground = Brushes.SkyBlue;
}
else
{
// Otherwise, change it to green
btnkey1.Background = Brushes.LightGreen;
btnkey1.Foreground = Brushes.White;
}

// Enable the interval combo box again (redundant, but included for
completeness)
comInterval.IsEnabled = true;

// Check if btnkey2 and btnkey1 are not green


if (btnkey2.Background != Brushes.LightGreen && btnkey1.Background !=
Brushes.LightGreen)
{
comInterval.IsEnabled = false;
btnKeyComStart.IsEnabled = false;
btnKeyComStart.Content = "Start"; // Update button text
combinedKeyTimer.Enabled = false; // Disable the timer
comInterval.SelectedIndex = -1;

}
}
private void Button_Click_7(object? sender,
Avalonia.Interactivity.RoutedEventArgs e)
{
comInterval.IsEnabled = true;
btnKeyComStart.IsEnabled = true;

if (btnkey2.Background == Brushes.LightGreen)
{
// If the background color is green, change it to transparent
btnkey2.Background = Brushes.WhiteSmoke;
btnkey2.Foreground = Brushes.SkyBlue;
}
else
{
// Otherwise, change it to green
btnkey2.Background = Brushes.LightGreen;
btnkey2.Foreground = Brushes.White;
}

// Enable the interval combo box (redundant, but included for clarity)
comInterval.IsEnabled = true;

// Check if btnkey2 and btnkey1 are not green


if (btnkey2.Background != Brushes.LightGreen && btnkey1.Background !=
Brushes.LightGreen)
{
comInterval.IsEnabled = false;
btnKeyComStart.IsEnabled = false;
btnKeyComStart.Content = "Start"; // Update button text
combinedKeyTimer.Enabled = false; // Disable the timer
comInterval.SelectedIndex = -1;
}

#region "Right Tab Actions"


string checkKeyPress = "ALT";
bool isAltPressed = false;
bool isTabPressed = false;

private void NoOfTabsTimer_Elapsed(object? sender,


System.Timers.ElapsedEventArgs e)
{

Dispatcher.UIThread.InvokeAsync(() =>
{
if (isAltPressed == true)
{
txtStatus.Text += "Alt Pressed-\n";
isAltPressed = false;
NoOfTabsTimer.Stop();
}
});
}
#endregion
private void RandomTabsTimer_Elapsed(object? sender,
System.Timers.ElapsedEventArgs e)
{
Dispatcher.UIThread.InvokeAsync(() =>
{
txtStatus.Text += "TAB Pressed-\n";
if (isAltPressed && isTabPressed)
{
NoOfTabsTimer.Stop();
RandomTabsTimer.Stop();
Random ran = new Random();
comInterval2.SelectedItem = ran.Next(2, 10).ToString();
isAltPressed = false;

if (comFirstKey.IsVisible == false)
{
comFirstKey.IsVisible = true;
// Key 2 Press 3 times
Button_Click_7(null, null);
Button_Click_7(null, null);
Button_Click_7(null, null);
}
else
{
comFirstKey.IsVisible = false;
comSecondKey.IsVisible = true;
// Key 1 Press 4 times
Button_Click_6(null, null);
Button_Click_6(null, null);
Button_Click_6(null, null);
Button_Click_6(null, null);
btnActivate.IsEnabled = true;
}
}
});
}

private void ActivateTimer_Elapsed(object? sender,


System.Timers.ElapsedEventArgs e)
{
Dispatcher.UIThread.InvokeAsync(() =>
{
// Stop the ActivateTimer and update the status
ActivateTimer.Stop();
txtStatus.Text += "Activate";

// Disable the Activate button


btnActivate.IsEnabled = false;
});
}

private void Button_Click_8(object? sender,


Avalonia.Interactivity.RoutedEventArgs? e)
{
combinedKeyTimer.Enabled = false;
btnKeyComStop.IsEnabled = false;
btnKeyComStart.IsEnabled = true;
comInterval.IsEnabled = true;
comFirstKey.IsEnabled = true;
}

private void Button_Click_10(object? sender,


Avalonia.Interactivity.RoutedEventArgs e)
{

trayIcon.IsVisible = false;
Environment.Exit(0);
}

TrayIcon trayIcon = new TrayIcon();


public void createTrayIcon()
{

// trayIcon.ToolTipText = "App Is Wroking";


trayIcon.Icon = new WindowIcon(new Bitmap(imagePath_));
trayIcon.Clicked += (s, e) =>
{
if (this.IsVisible)
{
this.ShowInTaskbar = false;
this.Hide();
}
else
{
this.ShowInTaskbar = true;
this.Show();
this.WindowState = WindowState.Normal;
}
};

var menu = new NativeMenu();

var startWindow = new NativeMenuItem("Start");


startWindow.Click += (sender, e) => StartWindow();

var exitWindow = new NativeMenuItem("Exit");


exitWindow.Click += (sender, e) => ExitWindow();

var showItem = new NativeMenuItem("Show Main Window");


showItem.Click += (sender, e) => ShowMainWindow();

var hideItem = new NativeMenuItem("Hide Main Window");


hideItem.Click += (sender, e) => HideMainWindow();

var exitItem = new NativeMenuItem("Exit App");


exitItem.Click += (sender, e) => ExitApp();

// Add a separator
var separator1 = new NativeMenuItemSeparator();
var separator2 = new NativeMenuItemSeparator();

// Add items to the menu


menu.Items.Add(startWindow);
menu.Items.Add(exitWindow);
menu.Items.Add(separator1);
menu.Items.Add(showItem);
menu.Items.Add(hideItem);
menu.Items.Add(separator2);
menu.Items.Add(exitItem);

trayIcon.Menu = menu;
trayIcon.IsVisible = true;

private void ExitWindow()


{

private void StartWindow()


{

private void ExitApp()


{
trayIcon.IsVisible = false;
Environment.Exit(0);
}

private void HideMainWindow()


{
this.Hide();
}

private void ShowMainWindow()


{
this.Show();
}

private void ToggleSwitch_IsCheckedChanged_11(object? sender,


Avalonia.Interactivity.RoutedEventArgs e)
{
var toggleSwitch = this.FindControl<ToggleSwitch>("toggleSwitch");

if (toggleSwitch.IsChecked == true)
{

TogglePanelPro.IsEnabled = true;
btnActivate.Content = "Activate";
comInterval2.IsEnabled = true;
comTabs.IsEnabled = true;
toggletabbutton.IsEnabled = true;
togglescreenbutton.IsEnabled = true;
toggleCursor.IsEnabled = true;
}
else if (toggleSwitch.IsChecked == false)
{
TogglePanelPro.IsEnabled = false;
btnActivate.Content = "Activate";
toggletabbutton.IsEnabled = false;
togglescreenbutton.IsEnabled = false;
toggleCursor.IsEnabled = false;
toggletabbutton.IsChecked = false;
togglescreenbutton.IsChecked = false;
toggleCursor.IsChecked = false;
toggleCursor.Content = "Enable Cursor Movement";

private void ComboBox_SelectionChanged_3(object? sender,


Avalonia.Controls.SelectionChangedEventArgs e)
{
}

private void Window_KeyUp_2(object? sender, Avalonia.Input.KeyEventArgs e)


{
// Check if the ALT key is released
if (e.Key == Avalonia.Input.Key.LeftAlt || e.Key ==
Avalonia.Input.Key.RightAlt) // Keys.Menu corresponds to the ALT key
{
// Stop the timer when the ALT key is released
NoOfTabsTimer.Stop();
// Reset the flag
isAltPressed = false;
}
else if (e.Key == Avalonia.Input.Key.Tab)
{
RandomTabsTimer.Stop();
// Reset the flag
isAltPressed = false;
}

private void Window_KeyDown_3(object? sender, Avalonia.Input.KeyEventArgs


e)
{
if (checkKeyPress == "ALT")
{
checkKeyPress = "TAB";
NoOfTabsTimer.Enabled = true;
NoOfTabsTimer.Start();
}
else if (checkKeyPress == "TAB")
{
isTabPressed = true;
checkKeyPress = "ALT";
NoOfTabsTimer.Enabled = false;
RandomTabsTimer.Enabled = true;
RandomTabsTimer.Start();
NoOfTabsTimer.Stop();
}
else
{
// No action for now
}

private void ComboBox_KeyDown_4(object? sender, Avalonia.Input.KeyEventArgs


e)
{
if (e.Key == Avalonia.Input.Key.LeftAlt || e.Key ==
Avalonia.Input.Key.RightAlt) // Checking for ALT key in Avalonia
{
isAltPressed = true;
isTabPressed = false;
}
else if (e.Key == Avalonia.Input.Key.Tab) // Checking for TAB key
{
txtStatus.Text += "TAB ";
isTabPressed = true;
}
}

private void Button_Click_12(object? sender,


Avalonia.Interactivity.RoutedEventArgs e)
{

// Toggle the activation based on current button text


if (btnActivate.Content.ToString() == "Activate")
{
// Check if selections are made
if (comTabs.SelectedIndex == -1)
{
var messageBox =
MessageBoxManager.GetMessageBoxStandard("Error", "Please select the number of
Tabs");
messageBox.ShowWindowDialogAsync(this);
return;
}

if (comInterval2.SelectedIndex == -1)
{
var messageBox =
MessageBoxManager.GetMessageBoxStandard("Error", "Please select an interval");
messageBox.ShowWindowDialogAsync(this);

return;
}

// Configure and start the timer based on selected values


totalTabs = int.Parse(comTabs.SelectedItem.ToString());
intervalTime = (int)
(Convert.ToDouble(comInterval2.SelectedItem.ToString()) * 60000); // Convert
minutes to milliseconds
shuffledTabs = Enumerable.Range(1, totalTabs).OrderBy(n =>
Guid.NewGuid()).ToList();

timer.Interval = intervalTime;
timer.AutoReset = true;
timer.Elapsed += OnTimedEvent;
timer.Start();

// Set UI to "running" state


btnActivate.Content = "Deactivate";
comTabs.IsEnabled = false; // Disable tabs combo box
comInterval2.IsEnabled = false; // Disable interval combo box
toggletabbutton.IsEnabled = false;
togglescreenbutton.IsEnabled = false;
toggleCursor.IsEnabled = false;
}
else
{
// Stop the timer and clean up
timer.Stop();
timer.Elapsed -= OnTimedEvent;

// Set UI to "not running" state


btnActivate.Content = "Activate";
comTabs.IsEnabled = true; // Enable tabs combo box
comInterval2.IsEnabled = true; // Enable interval combo box
toggletabbutton.IsEnabled = true;
togglescreenbutton.IsEnabled = true;
toggleCursor.IsEnabled = true;

comTabs.SelectedIndex = -1;
comInterval2.SelectedIndex = -1;
}

private void ToggleButton_Click_13(object? sender,


Avalonia.Interactivity.RoutedEventArgs e)
{
if (toggletabbutton.IsChecked == true)
{
togglescreenbutton.IsChecked = false;
lbl_selectNoTabs.Content = "Select No. of Tabs";
}
}

private void ToggleButton_Click_14(object? sender,


Avalonia.Interactivity.RoutedEventArgs e)
{
if (togglescreenbutton.IsChecked == true)
{

toggletabbutton.IsChecked = false;
lbl_selectNoTabs.Content = "Select No. of Screen";
}
}

private bool isToggled = false; // Track the toggle state


// Timer for periodic updates
private Random rand = new Random();
private void ToggleButton_Click_15(object? sender,
Avalonia.Interactivity.RoutedEventArgs e)
{
if (toggleCursor.IsChecked == true)
{
cursorTimer.Enabled = false;
cursorTimer.Interval = 5000;
cursorTimer.Start();
toggleCursor.Content = "Disable Cursor Movement"; // Update
button text
cursorTimer.Start(); // Start the timer
}
else
{
toggleCursor.Content = "Enable Cursor Movement"; // Update button
text
cursorTimer.Stop(); // Stop the timer
}
}

private void CursorTimer_Elapsed(object? sender,


System.Timers.ElapsedEventArgs e)
{

var screenWidth = Screens.Primary.Bounds.Width; // Set your screen


width
var screenHeight = Screens.Primary.Bounds.Height; // Set your screen
height

int x = rand.Next(screenWidth);
int y = rand.Next(screenHeight);

MoveCursor(x, y); // Cross-platform cursor movement


ScrollMouse(rand.Next(-1500,1500)); // Cross-platform mouse scroll
}

private void MoveCursor(int x, int y)


{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
SetCursorPos(x, y);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
X11MoveCursor(x, y);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
MacMoveCursor(x, y);
}
}

private void ScrollMouse(int delta)


{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
MouseScrollWindows(delta);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
X11ScrollMouse(delta);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
MacScrollMouse(delta);
}
}

// Windows APIs
[DllImport("user32.dll")]
private static extern bool SetCursorPos(int X, int Y);

[DllImport("user32.dll")]
private static extern void mouse_event(uint dwFlags, int dx, int dy, uint
dwData, UIntPtr dwExtraInfo);

private const uint MOUSEEVENTF_WHEEL = 0x0800;

private static void MouseScrollWindows(int scrollAmount)


{
mouse_event(MOUSEEVENTF_WHEEL, 0, 0, (uint)(scrollAmount),
UIntPtr.Zero);
}

// Linux (X11) APIs


private static void X11MoveCursor(int x, int y)
{
// Use X11 interop (requires libx11-dev)
throw new NotImplementedException("Implement X11 cursor movement");
}

private static void X11ScrollMouse(int delta)


{
// Use X11 interop for mouse scrolling
throw new NotImplementedException("Implement X11 mouse scrolling");
}

// macOS APIs
private static void MacMoveCursor(int x, int y)
{
// Use CoreGraphics for macOS cursor movement
throw new NotImplementedException("Implement macOS cursor movement");
}

private static void MacScrollMouse(int delta)


{
// Use CoreGraphics for macOS mouse scrolling
throw new NotImplementedException("Implement macOS mouse scrolling");
}

}
}

You might also like