The title might not make sense so I'll explain it more.
if (checkbox1.Checked && (RobloxPlayerBeta.exe is open)
{
api.Launch;
}
I want to make it so that the api launches if the checkbox is checked and the process is open.
Making a function to see if a process is active, is pretty straight forward. I have made a small example to show you.
Dont forget to use the following import:
using System.Diagnostics;
This is the function i'm using:
public bool IsProcessOpen(string name)
{
Process[] p = Process.GetProcessesByName(name); ///Get the process by a name
if(p.Length == 0) /// if the length of the array is 0, then it means its not running.
{
return false;
}
else /// if its other then 0 it means its its running.
{
return true;
}
}
I'm checking the answer with a simple button click on a Windows Forms application. I'm using the following:
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(IsProcessOpen(textBox1.Text).ToString());
///To test this function, you can try this by changing "textBox1.Text" to "cmd"
///If cmd is not opened, it will return false,
///If cmd is running, it will return True. You can also do this with other processes. For example Chrome
}
If you decide to copy this function, you're if statement should look something like this:
if (checkbox1.Checked == true && IsProcessOpen(RobloxPlayerBeta) == true)
{
api.Launch;
}
Hope this helps you out.
Twan
Related
Background: I'm creating an app that allows our other techs to quickly install a dozen or so programs within one simple GUI. I am embedding the installers of those apps within my main program. (not that it matters)
I created a separate class file (IsOfficeInstalled.cs) that gets called when a user clicks on a button to install Office. Here's the code in that file:
class IsOfficeInstalled
{
public static bool check()
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\Winword.exe");
if (key != null)
{
key.Close();
}
return key != null; }}
In my MainWindow.xaml file, I am trying to call the "IsOfficeInstalled" function and perform one of two actions based on the return value. This is where I am confused. The code in my button event looks like the following:
private void btn_InstallOffice_Click(object sender, RoutedEventArgs e)
if (IsOfficeInstalled.check())
{
//If yes, then perform some code
}
else
{
//If no, then perform some different code
}
Where I need help is, getting the true/false result back from the "IsOfficeInstalled" function so my code in the "btn_InstallOffice_Click" function will know which condition to execute.
I'm not sure if I'm understanding your question. Are you looking for a simple if statement?
private void btn_InstallOffice_Click(object sender, RoutedEventArgs e)
{
if (IsOfficeInstalled.check())
{
//If yes, then perform some code
}
else
{
//If no, then perform some different code
}
}
The problem is with the button:contains('Deal') selector, the button containing deal does exist on the page and Watin can find it without problems when running in main thread.
// Add bet, deal cards and wait for animation
private void dealCards()
{
// Start the game if chip exists
if (browser.Image(Find.BySrc(chipURL)).Exists)
{
browser.Image(Find.BySrc(chipURL)).Click();
// This is where the thread stops
browser.Button(Find.BySelector("button:contains('Deal')")).Click();
Thread.Sleep(dealCardsAnimationTime);
if (Convert.ToInt32(browser.Span(Find.ByClass("player-points")).Text) == 21)
{
consoleTextBox.AppendText("You won by blackjack.");
gameOver = true;
}
return;
}
}
Update:
Browser is a Internet Explore window that I interact with using WatiN, other than the UI changes, the problem seems to be that WatiN can't find the button.
However it's still somewhat related to multithreading, as the same code works fine without multithreading and the element that it's searching for does exist.
Update 2: Changed title and description of problem as the old one appeared to be unrelated.
Context ( in case it's necessary )
// When bet button is clicked
private void button2_Click(object sender, EventArgs e)
{
blackjackThread = new Thread(blackjackGame);
if (dealInProgress == false)
{
blackjackThread.Start();
// blackjackGame();
}
}
// Blackjack deal handler
private void blackjackGame()
{
consoleTextBox.AppendText("\r\n");
resetVariables();
dealCards();
if (gameOver == true)
{
checkResult();
dealInProgress = false;
blackjackThread.Abort();
return;
}
checkCards();
logPoints();
while (gameOver == false)
{
botAction();
}
checkResult();
dealInProgress = false;
blackjackThread.Abort();
return;
}
I am new to WPF and have been hunting for an answer, surely this is not difficult?
I have created a main window with links to multiple windows, and I want them to run modelessly alongside one another, but I don't want to open multiple instances of the SAME window.
In simple terms, I can have Windows A, B, C open at once, but not Windows, A, A, B, C, C.
I need to implement a check for the window I'm trying to open (in this case, EditSettings).
If open - activate it
if not open, open it.
I have the following code in Main, which is not working.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
EditSettings winEditSettings = new EditSettings();
string isOpen = null;
if (isOpen == "true")
{
winEditSettings.Activate();
}
else
{
winEditSettings.Show();
isOpen = "true";
}
}
}
Now I know what's wrong with this logic - every time I press the button to open EditSettings, it's setting isOpen to null again. If I don't set a value to isOpen, the If condition breaks.
I could initialise the variable 'isOpen' as a public variable outside the MenuItem_Click method, but then I think I would need an isOpen variable for each window I create!! Surely there is a better way?
The other option I tried is:
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
EditSettings winEditSettings = new EditSettings();
if (winEditSettings.IsLoaded)
{
winEditSettings.Activate();
}
else { winEditSettings.Show(); }
I can't figure out why this isn't working, I tried isVisible, isLoaded, isActive - nothing is stopping the window from opening more than once. Thank you for the help!
There are people who'll perhaps throw a fit at the idea, but whenever I've needed to do this, I made the child window objects part of the application. Then, in your MenuItem_Click(), test if winEditSettings is null, instead.
It's still a member variable for each window (like your provisional isOpen solution), but having the window objects available can have advantages later, if you need to bridge information between the windows. In my cases, we wanted to be able to close all the child windows together, which (most trivially) meant keeping track of those objects in a central location.
Alternatively, if you want the setup completely decoupled, you could take a singleton-like approach and put the logic into your child window classes. Specifically, you could call EditSettings.Activate and let the class keep track of whether a window needs to be created or the existing window merely Show()n.
If I were handed your code to rewrite, I'd move it something like this:
private static EditSettings winEditSettings = null;
public static void WakeUp()
{
if (winEditSettings == null)
{
winEditSettings = new EditSettings();
}
winEditSettings.Activate(); // This may need to be inside the block above
winEditSettings.Show();
}
Both of those are part of the class (static), rather than an instance. Your application object therefore calls EditSettings.WakeUp() inside the original MenuItem_Click(), and never actually sees the child window, itself.
If you change your mind about the decoupled architecture later, by the way, you can add a get accessor to your winEditSettings and keep everybody fairly happy.
if (_adCst == null)
{
_adCst = new AddCustomerPage();
_adCst.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
_adCst.WindowState = System.Windows.WindowState.Normal;
_adCst.ResizeMode = System.Windows.ResizeMode.NoResize;
_adCst.Activate(); // This may need to be inside the block above
_adCst.Show();
}
else
{
if (!_adCst.IsLoaded == true)
{
_adCst = new AddCustomerPage();
_adCst.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
_adCst.WindowState = System.Windows.WindowState.Normal;
_adCst.ResizeMode = System.Windows.ResizeMode.NoResize;
_adCst.Show();
}
_adCst.Activate();
}
My suggestion would be that you set some form of a counter. This will prevent more than one instance of the window being opened.
int windowOpen = 1;
private void button_Click(object sender, RoutedEventArgs e)
{
if (windowOpen == 1)
{
WindowA winA = new WindowA();
winA.Show();
windowOpen++; //increments windowOpen by 1, windowOpen will now = 2
}
else if (windowOpen > 1)
{
MessageBox.Show("Window is already open");
}
}
I hope this helps.
For anyone else with this question, I have found another solution - which works except that it doesn't manage to bring the open window to the front (Activate). It does, however, prevent opening the same window more than once.
foreach (Window n in Application.Current.Windows)
if (n.Name == "winEditSettings")
{ winEditSettings.Activate(); }
else
{ winEditSettings.Show(); }
Can anyone speculate on why the window is not brought to the front, with Activate()?
EDIT
For others with this question, placing the winEditSettings.Activate() outside of the foreach loop does everything I'm trying to achieve:
foreach (Window n in Application.Current.Windows)
if (n.Name == "winEditSettings")
{ }
else
{ winEditSettings.Show(); }
winEditSettings.Activate();
This will stop multiple instances of the same window from opening, and will bring the window to the front if the user attempts to reopen it.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("Are you Sure you want to Exit. Click Yes to Confirm and No to continue", "WinForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
e.Cancel = true;
}
else
{
Application.Exit();
}
}
Application.Exit(); for some reason make me to click twice YES before the program quit.
And It dosent close explorer windows like this:
Process.Start("explorer", String.Format("/select,{0}", t));
This explorer keep open when i quit my program.
Well, technically these windows do not belong to your application, so they should not be closed.
EDIT, regarding the comment: the solution provided below won't work, sorry, my mistake :)
If you really want to control explorer windows you've opened you can collect the return value of the Start method ( http://msdn.microsoft.com/en-us/library/53ezey2s.aspx ), and then call the Kill method on each of them ( http://msdn.microsoft.com/en-us/library/system.diagnostics.process.kill.aspx ). Remember to check if they still exist as the user might have closed them on their own.
Simple example for one window:
class Form
{
//...
private Process explorerWindow = null;
}
//...
this.explorerWindow = Process.Start("explorer", String.Format("/select,{0}", t));
//... (in OnFormClosing)
if (this.explorerWindow != null && !this.explorerWindow.HasExited)
{
this.explorerWindow.Kill();
}
Do similar, but with the List. You could also hook up to the OnExited event and remove particular processes from the list, when they disappear (f.e. because the user closed them).
The 'click sound' in question is actually a system wide preference, so I only want it to be disabled when my application has focus and then re-enable when the application closes/loses focus.
Originally, I wanted to ask this question here on stackoverflow, but I was not yet in the beta. So, after googling for the answer and finding only a little bit of information on it I came up with the following and decided to post it here now that I'm in the beta.
using System;
using Microsoft.Win32;
namespace HowTo
{
class WebClickSound
{
/// <summary>
/// Enables or disables the web browser navigating click sound.
/// </summary>
public static bool Enabled
{
get
{
RegistryKey key = Registry.CurrentUser.OpenSubKey(#"AppEvents\Schemes\Apps\Explorer\Navigating\.Current");
string keyValue = (string)key.GetValue(null);
return String.IsNullOrEmpty(keyValue) == false && keyValue != "\"\"";
}
set
{
string keyValue;
if (value)
{
keyValue = "%SystemRoot%\\Media\\";
if (Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor > 0)
{
// XP
keyValue += "Windows XP Start.wav";
}
else if (Environment.OSVersion.Version.Major == 6)
{
// Vista
keyValue += "Windows Navigation Start.wav";
}
else
{
// Don't know the file name so I won't be able to re-enable it
return;
}
}
else
{
keyValue = "\"\"";
}
// Open and set the key that points to the file
RegistryKey key = Registry.CurrentUser.OpenSubKey(#"AppEvents\Schemes\Apps\Explorer\Navigating\.Current", true);
key.SetValue(null, keyValue, RegistryValueKind.ExpandString);
isEnabled = value;
}
}
}
}
Then in the main form we use the above code in these 3 events:
Activated
Deactivated
FormClosing
private void Form1_Activated(object sender, EventArgs e)
{
// Disable the sound when the program has focus
WebClickSound.Enabled = false;
}
private void Form1_Deactivate(object sender, EventArgs e)
{
// Enable the sound when the program is out of focus
WebClickSound.Enabled = true;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// Enable the sound on app exit
WebClickSound.Enabled = true;
}
The one problem I see currently is if the program crashes they won't have the click sound until they re-launch my application, but they wouldn't know to do that.
What do you guys think? Is this a good solution? What improvements can be made?
const int FEATURE_DISABLE_NAVIGATION_SOUNDS = 21;
const int SET_FEATURE_ON_PROCESS = 0x00000002;
[DllImport("urlmon.dll")]
[PreserveSig]
[return: MarshalAs(UnmanagedType.Error)]
static extern int CoInternetSetFeatureEnabled(int FeatureEntry,
[MarshalAs(UnmanagedType.U4)] int dwFlags,
bool fEnable);
static void DisableClickSounds()
{
CoInternetSetFeatureEnabled(FEATURE_DISABLE_NAVIGATION_SOUNDS,
SET_FEATURE_ON_PROCESS,
true);
}
I've noticed that if you use WebBrowser.Document.Write rather than WebBrowser.DocumentText then the click sound doesn't happen.
So instead of this:
webBrowser1.DocumentText = "<h1>Hello, world!</h1>";
try this:
webBrowser1.Document.OpenNew(true);
webBrowser1.Document.Write("<h1>Hello, world!</h1>");
You disable it by changing Internet Explorer registry value of navigating sound to "NULL":
Registry.SetValue("HKEY_CURRENT_USER\\AppEvents\\Schemes\\Apps\\Explorer\\Navigating\\.Current","","NULL");
And enable it by changing Internet Explorer registry value of navigating sound to "C:\Windows\Media\Cityscape\Windows Navigation Start.wav":
Registry.SetValue("HKEY_CURRENT_USER\\AppEvents\\Schemes\\Apps\\Explorer\\Navigating\\.Current","","C:\Windows\Media\Cityscape\Windows Navigation Start.wav");
Definitely feels like a hack, but having done some research on this a long time ago and not finding any other solutions, probably your best bet.
Better yet would be designing your application so it doesn't require many annoying page reloads.. for example, if you're refreshing an iframe to check for updates on the server, use XMLHttpRequest instead. (Can you tell that I was dealing with this problem back in the days before the term "AJAX" was coined?)
If you want to use replacing Windows Registry, use this:
// backup value
RegistryKey key = Registry.CurrentUser.OpenSubKey(#"AppEvents\Schemes\Apps\Explorer\Navigating\.Current");
string BACKUP_keyValue = (string)key.GetValue(null);
// write nothing
key = Registry.CurrentUser.OpenSubKey(#"AppEvents\Schemes\Apps\Explorer\Navigating\.Current", true);
key.SetValue(null, "", RegistryValueKind.ExpandString);
// do navigation ...
// write backup key
RegistryKey key = Registry.CurrentUser.OpenSubKey(#"AppEvents\Schemes\Apps\Explorer\Navigating\.Current", true);
key.SetValue(null, BACKUP_keyValue, RegistryValueKind.ExpandString);