Switching to another application (previously active) on button click in .net - switch-statement

Hi I want to do something like on screen keyboard. I want user to click a button on inactive application and then key press will be sent to active application while keeping active application active. I wrote the code for hover event of the button in inactive application and it is working. But what I want is to do it in click event. It is not working because inactive application becomes active. The code is below for hover event. Thank you.
private void button1_MouseHover(object sender, EventArgs e)
{
SendKeys.Send("{TAB}");
}

Finally I could figure out a way to do it.
Refer the code below.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Timers;
using tmr = System.Timers;
using System.Threading;
namespace KeyPressTest
{
public partial class Form1 : Form
{
[DllImport("user32.dll")]
static extern int GetForegroundWindow();
[DllImport("user32")]
private static extern UInt32 GetWindowThreadProcessId(Int32 hWnd, out Int32 lpdwProcessId);
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
tmr.Timer tm = new tmr.Timer();
Int32 hwnd = 0;
private Int32 GetWindowProcessID(Int32 hwnd)
{
Int32 pid = 1;
GetWindowThreadProcessId(hwnd, out pid);
return pid;
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
tm.Elapsed += Timer_Elapsed;
tm.Interval = 100;
tm.Start();
}
private void button1_Click(object sender, EventArgs e)
{
SetForegroundWindow((IntPtr)hwnd);
Thread.Sleep(40);
SendKeys.Send("{TAB}");
}
private void Timer_Elapsed(object sender, System.EventArgs args)
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(delegate
{
if (this.Handle.ToInt32() != GetForegroundWindow())
{
hwnd = GetForegroundWindow();
}
}));
}
else
{
if (this.Handle.ToInt32() != GetForegroundWindow())
{
hwnd = GetForegroundWindow();
}
}
if (hwnd == 0)
{
return;
}
string appProcessName = "";
string appExePath = "";
string appExeName = "";
try
{
appProcessName = Process.GetProcessById(GetWindowProcessID(hwnd)).ProcessName;
appExePath = Process.GetProcessById(GetWindowProcessID(hwnd)).MainModule.FileName;
appExeName = appExePath.Substring(appExePath.LastIndexOf(#"\") + 1);
}
catch (Exception ex)
{
}
if (textBox1.InvokeRequired)
{
textBox1.Invoke(new MethodInvoker(delegate
{
textBox1.Text = appProcessName + " | " + appExePath + " | " + appExeName;
}));
}
else
{
textBox1.Text = appProcessName + " | " + appExePath + " | " + appExeName;
}
}
}
}

I have never done something similar, but here is what I found in this forum:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
[DllImport("user32.dll")]
static extern int GetForegroundWindow();
[DllImport("user32")]
private static extern UInt32 GetWindowThreadProcessId(Int32 hWnd, out Int32 lpdwProcessId);
private int teller = 0;
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (teller == 1)
{
setTextje();
}
teller++;
}
private Int32 GetWindowProcessID(Int32 hwnd)
{
Int32 pid = 1;
GetWindowThreadProcessId(hwnd, out pid);
return pid;
}
private void setTextje()
{
Int32 hwnd = 0;
hwnd = GetForegroundWindow();
string appProcessName = Process.GetProcessById(GetWindowProcessID(hwnd)).ProcessName;
string appExePath = Process.GetProcessById(GetWindowProcessID(hwnd)).MainModule.FileName;
string appExeName = appExePath.Substring(appExePath.LastIndexOf(#"\") + 1);
textBox1.Text = appProcessName + " | " + appExePath + " | " + appExeName;
}
}
}
It doesn't answer exactly to your question but it will give you a hint. You need to DllImport "User32.dll". After that you can get the id of the foreground window and play with that.
There is also a very interesting article about application switch tracking written in C#

Related

Error in save video from webcam video c#

I need some help with error..
Error 2 The type 'AForge.Video.NewFrameEventArgs' exists in both 'c:\Users\anton\OneDrive\Документы\Visual Studio 2013\Projects\WindowsFormsApplication4\packages\Accord.Video.3.0.2\lib\net45\Accord.Video.dll' and 'c:\Users\anton\OneDrive\Documents\Visual Studio 2013\Projects\WindowsFormsApplication4\packages\AForge.Video.2.2.5\lib\AForge.Video.dll' C:\Users\anton\onedrive\Documents\visual studio 2013\Projects\WindowsFormsApplication4\WindowsFormsApplication4\Form1.cs 50 42 WindowsFormsApplication4
this is my code:`
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AForge.Video;
using AForge.Video.DirectShow;
using AForge.Video.FFMPEG;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private VideoCaptureDevice FinalVideo = null;
private VideoCaptureDeviceForm captureDevice;
private Bitmap video;
private VideoFileWriter FileWriter = new VideoFileWriter();
private SaveFileDialog saveAvi;
private FilterInfoCollection webcam;
private VideoCaptureDevice cam;
private void Form1_Load(object sender, EventArgs e)
{
webcam = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo VideoCaptureDevice in webcam)
{
comboBox1.Items.Add(VideoCaptureDevice.Name);
comboBox1.SelectedIndex = 0;
}
pictureBox1.Anchor = (AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Bottom);
comboBox1.Anchor = (AnchorStyles.Bottom);
button1.Anchor = (AnchorStyles.Bottom);
button2.Anchor = (AnchorStyles.Bottom);
button3.Anchor = (AnchorStyles.Bottom);
}
private void button1_Click(object sender, EventArgs e)
{
cam = new VideoCaptureDevice(webcam[comboBox1.SelectedIndex].MonikerString);
cam.NewFrame += new NewFrameEventHandler(cam_NewFrame);
cam.Start();
}
void cam_NewFrame(object sender, NewFrameEventArgs EventArgs)
{
Bitmap bit = (Bitmap)EventArgs.Frame.Clone();
pictureBox1.Image = bit;
}
private void button3_Click(object sender, EventArgs e)
{
if (cam.IsRunning)
{
cam.Stop();
}
}
private void button2_Click(object sender, EventArgs e)
{
saveFileDialog1.InitialDirectory = #"C:\picture";
saveFileDialog1.Filter = "Images|*.png;*.bmp;*.jpg";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image.Save(saveFileDialog1.FileName);
}
}
private void button4_Click(object sender, EventArgs e)
{
saveAvi = new SaveFileDialog();
saveAvi.Filter = "Avi Files (*.avi)|*.avi";
if (saveAvi.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
int h = captureDevice.VideoDevice.VideoResolution.FrameSize.Height;
int w = captureDevice.VideoDevice.VideoResolution.FrameSize.Width;
FileWriter.Open(saveAvi.FileName, w, h, 25, VideoCodec.Default, 5000000);
FileWriter.WriteVideoFrame(video);
//AVIwriter.Open(saveAvi.FileName, w, h);
//FinalVideo = captureDevice.VideoDevice;
//FinalVideo.NewFrame += new NewFrameEventHandler(FinalVideo_NewFrame);
//FinalVideo.Start();
}
}
}
}

OxyPlot EventTrigger

I am trying to handle event in OxyPlot using EventTrigger. But it does not work like I want.
<Window x:Class="WpfApplication14.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:oxy="http://oxyplot.org/wpf"
Title="MainWindow" Height="350" Width="525">
<Grid>
<oxy:PlotView Model="{Binding PlotModel}" DefaultTrackerTemplate="{x:Null}">
<i:Interaction.Triggers >
<i:EventTrigger EventName="MouseDown">
<i:InvokeCommandAction Command="{Binding Move}"></i:InvokeCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>
</oxy:PlotView>
</Grid>
And code look's like
using OxyPlot;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using OxyPlot.Axes;
using GalaSoft.MvvmLight.Command;
namespace WpfApplication14
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
///
public partial class MainWindow : Window
{
public class DataGeneration
{
public PlotModel PlotModel { get; set; }
public ICommand Move { get; set; }
public int _NumberOf;
public Dictionary<int, List<int>> Test { get; set; }
OxyPlot.Series.LineSeries LS;
Random rnd;
LinearAxis LA;
public int EndPosition = 0;
public DataGeneration(int NumberOf)
{
LA = new LinearAxis()
{
Position=AxisPosition.Bottom,
Minimum=0,
Maximum = EndPosition
};
Move = new RelayCommand(() => TestMove());
_NumberOf = NumberOf;
rnd = new Random();
Test = new Dictionary<int, List<int>>();
PlotModel = new PlotModel();
PlotModel.Axes.Add(LA);
LS = new OxyPlot.Series.LineSeries();
PlotModel.Series.Add(LS);
}
public void TestMove()
{
PlotModel.Axes[0].Reset();
}
public void AddPoint()
{
do
{
LS.Points.Add(new DataPoint(++_NumberOf, rnd.Next(1, 10)));
System.Threading.Thread.Sleep(1000);
EndPosition += 1;
LA.Maximum = EndPosition+3;
LA.Minimum = EndPosition;
Update();
} while (true);
}
public void Update()
{
PlotModel.InvalidatePlot(true);
}
}
public delegate void BeginUpdate();
private Stopwatch stopwatch = new Stopwatch();
private long lastUpdateMilliSeconds;
DataGeneration Data;
public MainWindow()
{
Data = new DataGeneration(1);
BeginUpdate BU = new BeginUpdate(Data.AddPoint);
IAsyncResult result = BU.BeginInvoke(null, null);
this.DataContext = Data;
CompositionTarget.Rendering += CompositionTargetRendering;
InitializeComponent();
}
private void CompositionTargetRendering(object sender, EventArgs e)
{
if (stopwatch.ElapsedMilliseconds > lastUpdateMilliSeconds + 300)
{
Data.Update();
}
}
}
}
why it firing when I make double click on OxyPlot? Genaraly i am trying to pan chart by left mousebutton.It's implemented in oxyplot by default(right mouse button).

How to create extension for VS2012 using VS Package on File Save Event

I need to create an extension to do some custom activity, on File Save Event in visual studio. How to achieve this using VS Package.
I am struck with below code, any advise?
#region Package Members
FileEventsListener listener = null;
protected override void Initialize()
{
Debug.WriteLine (string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString()));
base.Initialize();
listener = new FileEventsListener();
}
#endregion
}
public class FileEventsListener : IPersistFileFormat, IDisposable
{
private IVsSolution solution;
private uint solutionEventsCookie;
private bool isDirty;
private string fileName;
private const uint MyFormat = 0;
private const string MyExtension = ".edmx";
public FileEventsListener()
{
//solution = Package.GetGlobalService(typeof(SPersistFileFormat)) as IVsSolution;
//if (solution != null)
//{
// solution.AdviseSolutionEvents(this, out solutionEventsCookie);
//}
}
#region IDisposable Members
public void Dispose()
{
}
#endregion
public int GetClassID(out Guid pClassID)
{
ErrorHandler.ThrowOnFailure(((IPersist)this).GetClassID(out pClassID));
return VSConstants.S_OK;
}
public int GetCurFile(out string ppszFilename, out uint pnFormatIndex)
{
pnFormatIndex = MyFormat;
ppszFilename = fileName;
return VSConstants.S_OK;
}
public int GetFormatList(out string ppszFormatList)
{
char Endline = (char)'\n';
string FormatList = string.Format(CultureInfo.InvariantCulture, "My Editor (*{0}){1}*{0}{1}{1}", MyExtension, Endline);
ppszFormatList = FormatList;
return VSConstants.S_OK;
}
public int InitNew(uint nFormatIndex)
{
if (nFormatIndex != MyFormat)
{
return VSConstants.E_INVALIDARG;
}
// until someone change the file, we can consider it not dirty as
// the user would be annoyed if we prompt him to save an empty file
isDirty = false;
return VSConstants.S_OK;
}
public int IsDirty(out int pfIsDirty)
{
pfIsDirty = 0;
return VSConstants.S_OK;
}
public int Load(string pszFilename, uint grfMode, int fReadOnly)
{
fileName = pszFilename;
return VSConstants.S_OK;
}
public int Save(string pszFilename, int fRemember, uint nFormatIndex)
{
return VSConstants.S_OK;
}
public int SaveCompleted(string pszFilename)
{
return VSConstants.S_OK;
}
}
}
You can subscribe to the DTE.Events.DocumentEvents.DocumentSaved event.

Running control.exe as process does not WaitForExit()

I am running control.exe as a process. (Windows 7 OS, .NET 3.5, C#). It does not stop at WaitForExit() as expected. It immediately "exits" the process even though the control.exe window is still open. I have tried the process.Exited event also and that is triggered before the application exits as well.
Here is my code:
Process process = new Process();
process.StartInfo.FileName = #"c:\windows\system32\control.exe";
process.StartInfo.Arguments = #"userpasswords";
process.Start();
process.WaitForExit();
Send from phone (please correct my formatting, would take hours by phone)
Try to check if window is visible or task is running like:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace yournamespace
{
class FormCheck
{
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, IntPtr windowTitle);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, int wParam, StringBuilder lParam);
const int WM_GETTEXT = 0x000D;
const int WM_GETTEXTLENGTH = 0x000E;
public static bool IsRunning(string window, bool exactfit)
{ return Check(window,exactfit); }
public static bool IsRunning(string window)
{ return Check(window); }
public static bool Check(string Processname)
{
Process[] pname = Process.GetProcessesByName(Processname);
if (pname.Length <= 1) { return false; } else { return true; }
}
public static bool Check(string WindowTitle, bool exactfit)
{
bool response = false;
string[] strWindowsTitles = EnumerateOpenedWindows.GetDesktopWindowsTitles();
string strResponse = "";
foreach (string strTitle in strWindowsTitles)
{
if (strTitle.Contains(WindowTitle))
{
if (exactfit)
{
if (strTitle == WindowTitle)
{
strResponse = strTitle;
break;
}
}
else
{
if (strTitle.Contains(WindowTitle))
{
strResponse = strTitle;
break;
}
}
}
}
string pid = string.Empty;
if (strResponse != "")
{
response = true;
}
else { response = false; }
return response;
}
}
public class EnumerateOpenedWindows
{
const int MAXTITLE = 255;
private static List<string> lstTitles;
private delegate bool EnumDelegate(IntPtr hWnd, int lParam);
[DllImport("user32.dll", EntryPoint = "EnumDesktopWindows",
ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool EnumDesktopWindows(IntPtr hDesktop,
EnumDelegate lpEnumCallbackFunction, IntPtr lParam);
[DllImport("user32.dll", EntryPoint = "GetWindowText",
ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)]
private static extern int _GetWindowText(IntPtr hWnd,
StringBuilder lpWindowText, int nMaxCount);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool IsWindowVisible(IntPtr hWnd);
private static bool EnumWindowsProc(IntPtr hWnd, int lParam)
{
string strTitle = GetWindowText(hWnd);
if (strTitle != "" & IsWindowVisible(hWnd)) //
{
lstTitles.Add(strTitle);
}
return true;
}
/// <summary>
/// Return the window title of handle
/// </summary>
/// <param name="hWnd"></param>
/// <returns></returns>
public static string GetWindowText(IntPtr hWnd)
{
StringBuilder strbTitle = new StringBuilder(MAXTITLE);
int nLength = _GetWindowText(hWnd, strbTitle, strbTitle.Capacity + 1);
strbTitle.Length = nLength;
return strbTitle.ToString();
}
/// <summary>
/// Return titles of all visible windows on desktop
/// </summary>
/// <returns>List of titles in type of string</returns>
public static string[] GetDesktopWindowsTitles()
{
lstTitles = new List<string>();
EnumDelegate delEnumfunc = new EnumDelegate(EnumWindowsProc);
bool bSuccessful = EnumDesktopWindows(IntPtr.Zero, delEnumfunc, IntPtr.Zero); //for current desktop
if (bSuccessful)
{
return lstTitles.ToArray();
}
else
{
// Get the last Win32 error code
int nErrorCode = Marshal.GetLastWin32Error();
string strErrMsg = String.Format("EnumDesktopWindows failed with code {0}.", nErrorCode);
throw new Exception(strErrMsg);
}
}
}
}
By using one of the methods of "isrunning" like:
int waiter = 0;
while (isRunning("Control")
{
//add 1 to an value and set to zero after x counts
waiter++;
if (waiter == 1000) { waiter=0; }
}
Your program will stuck until control shut down. Escaping sequences should inserted if control would never shut down again ;)

Make the text go bold after button press

I have a form in C# that has some buttons. I want that when the button is pressed, make the text bold.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Net;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// string str = #"C:\windows\system32\notepad.exe";
// string str = #"C:\windows\system32\winamp.exe";
string str = #"C:\priority\bin.95\WINMENU.exe";
Process process = new Process();
process.StartInfo.FileName = str;
process.Start();
}
private void button2_Click(object sender, EventArgs e)
{
// string str = #"C:\windows\system32\notepad.exe";
// string str = #"C:\windows\system32\winamp.exe";
string str = #"C:\Program Files\UltraVNC\vncviewer.exe";
Process process = new Process();
process.StartInfo.FileName = str;
process.Start();
}
private void button3_Click(object sender, EventArgs e)
{
}
private void button3_Click_1(object sender, EventArgs e)
{
// string str = #"C:\windows\system32\notepad.exe";
// string str = #"C:\windows\system32\winamp.exe";
string str = #"C:\Program Files\UltraVNC\vncviewer.exe";
Process process = new Process();
process.StartInfo.FileName = str;
process.Start();
}
private void button4_Click(object sender, EventArgs e)
{
// string str = #"C:\windows\system32\notepad.exe";
// string str = #"C:\windows\system32\winamp.exe";
string str = #"C:\Windows\system32\mstsc.exe";
Process process = new Process();
process.StartInfo.FileName = str;
process.Start();
}
private void button5_Click(object sender, EventArgs e)
{
// string str = #"C:\windows\system32\notepad.exe";
// string str = #"C:\windows\system32\winamp.exe";
string str = #"C:\Program Files\Microsoft Office\Office14\winword.exe";
Process process = new Process();
process.StartInfo.FileName = str;
process.Start();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
}
}
what should I do now ?
Use the Click event for the button, something like this:
private void button_Click(object sender, EventArgs e)
{
Button b = ((Button)sender);
b.Font = new Font(b.Font, FontStyle.Bold);
}
#hyprsleepy - i dont think that your answer can work because the property Button.Font.Bold is read only so you can only read the value to see what it is currently set as.
#asher - where you have these events:
private void button5_Click(object sender, EventArgs e)
{
// string str = #"C:\windows\system32\notepad.exe";
// string str = #"C:\windows\system32\winamp.exe";
string str = #"C:\Program Files\Microsoft Office\Office14\winword.exe";
Process process = new Process();
process.StartInfo.FileName = str;
process.Start();
}
use similar syntax to this:
private void button5_Click(object sender, EventArgs e)
{
// string str = #"C:\windows\system32\notepad.exe";
// string str = #"C:\windows\system32\winamp.exe";
string str = #"C:\Program Files\Microsoft Office\Office14\winword.exe";
Process process = new Process();
process.StartInfo.FileName = str;
process.Start();
Button b = ((Button)sender);
b.Font = new Font(b.Font, FontStyle.Bold);
}
Here is the code:
private void button1_Click(object sender, EventArgs e)
{
button1.Font = new Font(this.Font, FontStyle.Bold);
}

Resources