Get outlook Active window handle hwnd in C# - c#

I want to get the outlook Active window handle (hwnd) in C#. I want to use this for SendMessage() method which takes hwnd as first parameter. Outlook is open and not minimized. Tried to do like this..
dynamic winHwnd= Globals.ThisAddIn.Application.ActiveWindow();
Not working as type mismatches . Even if i convert it doesn't work. Could some one suggest me to get this handler..

Maybe you could try to use generic approach by using system Api FindWindow to get the window you interested by it's name:
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
IntPtr hWnd = (IntPtr)FindWindow(windowName, null);
From ActiveWindow you could try:
dynamic activeWindow = Globals.ThisAddIn.Application.ActiveWindow();
IntPtr outlookHwnd = new OfficeWin32Window(activeWindow).Handle;

You probably want to use the GetActiveWindow api function.
[DllImport("user32.dll")]
static extern IntPtr GetActiveWindow();
IntPtr handle = GetActiveWindow();
Try and minimize the window to see if you are getting the correct handle.
private const int SW_SHOWMINIMIZED = 2;
[DllImport("user32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow)
ShowWindowAsync(hWnd, SW_SHOWMINIMIZED);

Cast the Inspector object to the IOleWindow interface and call IOleWindow::GetWindow. The same will work for the Explorer object.

Related

Sending a string of characters as a keystroke to any application in WPF [duplicate]

I want to simulate F5 key press in my C# program. When IE is open, I want to be able refresh my website automatically.
How can I do that?
Here's an example...
static class Program
{
[DllImport("user32.dll")]
public static extern int SetForegroundWindow(IntPtr hWnd);
[STAThread]
static void Main()
{
while(true)
{
Process [] processes = Process.GetProcessesByName("iexplore");
foreach(Process proc in processes)
{
SetForegroundWindow(proc.MainWindowHandle);
SendKeys.SendWait("{F5}");
}
Thread.Sleep(5000);
}
}
}
a better one... less anoying...
static class Program
{
const UInt32 WM_KEYDOWN = 0x0100;
const int VK_F5 = 0x74;
[DllImport("user32.dll")]
static extern bool PostMessage(IntPtr hWnd, UInt32 Msg, int wParam, int lParam);
[STAThread]
static void Main()
{
while(true)
{
Process [] processes = Process.GetProcessesByName("iexplore");
foreach(Process proc in processes)
PostMessage(proc.MainWindowHandle, WM_KEYDOWN, VK_F5, 0);
Thread.Sleep(5000);
}
}
}
You can use the Win32 API FindWindow or FindWindowEx to find the window handle of the open browser and then just call SendMessage with WM_KEYDOWN. Typically it's easiest just to pass the window caption to FindWindowEx and have it find the associated window handle for you.
If you are starting the browser process yourself via a Process process object then you can use process.MainWindowHandle instead of calling FindWindowEx.
Spy++ is a very useful tool when you want to start working with other windows. It basically allows you to learn another program's hierarchy of UI elements. You can also monitor all of the messages that go into the window you're monitoring. I have more info in this thread.
The F5 keystroke has this virtual key code:
const int VK_F5 = 0x74;
The p/invoke signature for FindWindowEx in C# is:
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
You can p/invoke (bring in) the Win32 API SendMessage like this:
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
So to recap, you call FindWindowEx directly from your C# code after having the above code somewhere inside your class. FindWindowEx will return a window handle. Then once you have the window handle, you can send any keystroke(s) to the window, or call many other Win32 API calls on the window handle. Or even find a child window by using another call to FindWindowEx. For example you could select the edit control of the browser even and then change it's text.
If all else goes wrong and you think you're sending the right key to the window, you can use spy++ to see what messages are sent to the window when you manually set focus to the browser and manually press F5.
The easiest way to send (simulate) KeyStrokes to any window is to use the SendKeys.Send method of .NET Framework.
Checkout this very intuitive MSDN article http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.aspx
Particularly for your case, if your browser window is in focus, sending F5 would just involve the following line of code:
SendKeys.Send("{F5}");
Simple one, add before Main
[DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
Code inside Main/Method:
string className = "IEFrame";
string windowName = "New Tab - Windows Internet Explorer";
IntPtr IE = FindWindow(className, windowName);
if (IE == IntPtr.Zero)
{
return;
}
SetForegroundWindow(IE);
InputSimulator.SimulateKeyPress(VirtualKeyCode.F5);
Note:
Add InputSimulator as reference. To download Click here
To find Class & Window name, use WinSpy++. To download Click here
Another alternative to simulating a F5 key press would be to simply host the WebBrowser control in the Window Forms application. You use the WebBrowser.Navigate method to load your web page and then use a standard Timer and on each tick of the timer you just re-Navigate to the url which will reload the page.
Easy, short and no need window focus:
Also here a usefull list of Virtual Key Codes
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
static extern bool PostMessage(IntPtr hWnd, UInt32 Msg, int wParam, int lParam);
private void button1_Click(object sender, EventArgs e)
{
const int WM_SYSKEYDOWN = 0x0104;
const int VK_F5 = 0x74;
IntPtr WindowToFind = FindWindow(null, "Google - Mozilla Firefox");
PostMessage(WindowToFind, WM_SYSKEYDOWN, VK_F5, 0);
}
Use mouse_event or keybd_event. They say not to use them anymore but you don't have to find the window at all.
using System;
using System.Runtime.InteropServices;
public class SimulatePCControl
{
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern void keybd_event(uint bVk, uint bScan, uint dwFlags, uint dwExtraInfo);
private const int VK_LEFT = 0x25;
public static void LeftArrow()
{
keybd_event(VK_LEFT, 0, 0, 0);
}
}
Virtual Key Codes are here for this one: http://www.kbdedit.com/manual/low_level_vk_list.html
Also for mouse:
using System.Runtime.InteropServices;
using UnityEngine;
public class SimulateMouseClick
{
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, uint dwExtraInfo);
//Mouse actions
private const int MOUSEEVENTF_LEFTDOWN = 0x02;
private const int MOUSEEVENTF_LEFTUP = 0x04;
private const int MOUSEEVENTF_RIGHTDOWN = 0x08;
private const int MOUSEEVENTF_RIGHTUP = 0x10;
public static void Click()
{
//Call the imported function with the cursor's current position
uint X = (uint)0;
uint Y = (uint)0;
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0);
Debug.LogError("SIMULATED A MOUSE CLICK JUST NOW...");
}
//...other code needed for the application
}
Instead of forcing an F5 keypress when you're just trying to get the page to postback, you can call a postback based on a JS event (even mousemove or timer_tick if you want it to fire all the time). Use the code at http://weblogs.asp.net/mnolton/archive/2003/06/04/8260.aspx as a reference.

Access pop-up window button via API in C#

I'm building a plug-in in a structural design software and I'm using C# to access the API. All the geometric definitions, materials, verifications etc are fine. I use a button in the app to run the calculations. When the calcs are done the attached window pops up.
As part of a recursive process I'm trying to automatically press "Yes" from the API using SendMessage but I can't make it work. The code looks like this:
[DllImport("user32.dll")]
public static extern int FindWindow(string lpclassName, string lpWindowName);
[DllImport("user32.dll")]
public static extern int SendMessage(int hWnd, uint msg, int wParam, int lParam);
int WindowToFind = FindWindow(null, "Autodesk Robot Structural Analysis Professional 2014");
SendMessage(WindowToFind, WM_LBUTTONDOWN, 0, 0);
Does anyone know a better way to approach this (maybe mouse_event)?
Help will be much appreciated.
Best,
At a high level, I'd give a few options:
Use Windows API plus the AutomationElement class. You should be able to do the "Invoke" automation pattern to click the button. For me, this would be the preferred way to do this.
Use Windows API plus SendInput to use keyboard (or mouse) to click the button.
Look into the AutomationElement class: http://msdn.microsoft.com/en-us/library/system.windows.automation.automationelement%28v=vs.110%29.aspx
You will probably want to find "uispy" or some other utility for looking at AutomationElements. Another option is to wait for the window title to change to what you are looking for - assuming that the dialog has a different window title than the main window.
Some helpful apis are:
[DllImport( "user32.dll", SetLastError = true )]
public static extern IntPtr GetForegroundWindow();
/// <summary>
/// gets the window title of the foreground window
/// </summary>
public static string GetWindowTitle()
{
return GetWindowText( GetForegroundWindow() );
}
public static string GetWindowText( IntPtr hWnd )
{
int length = GetWindowTextLength( hWnd );
StringBuilder text = new StringBuilder( length + 1 );
GetWindowText( hWnd, text, text.Capacity );
return text.ToString();
}
[DllImport( "user32.dll", SetLastError = true, CharSet = CharSet.Auto )]
public static extern int GetWindowTextLength( IntPtr hwnd );
[DllImport( "user32.dll" )]
private static extern int GetWindowText( IntPtr hWnd, StringBuilder lpString, int nMaxCount );
You could use keyboard input to send the keys:
You could check out this:
http://inputsimulator.codeplex.com/

Disable minimize button in internet explorer opened in a Citrix instance

I've disabled the system menu buttons in the past on many windows using GetWindowLong (or GetWindowLongPtr if 64-bit) and SetWindowLong (or SetWindowLongPtr) with great success. I have a Citrix session that launches internet explorer and I cannot get these items to be removed from the title bar. I know the method that I am using is working because I can do what I want to do when a normal, non-Citrix, internet explorer is open. I successfully get the window handle for the Citrix IE session as I can focus it, set it to topmost, etc. It just does not want to work with Get/SetWindowLong and is obviously something to do with Citrix. Ignore the attribute parameter - I will eventually be passing in what WS_ will be used to manipulate the window, but I just want to keep it simple until I get this working (if it is even possible).
[DllImport("user32.dll")]
internal extern static long SetWindowLong(int hwnd, int index, long value);
[DllImport("user32.dll")]
internal extern static long GetWindowLong(int hwnd, int index);
public static void SetWindowAttribute(int hwnd, int attribute)
{
IntPtr hwndPtr = new IntPtr(hwnd);
const int GWL_STYLE = -16;
const long WS_MINIMIZEBOX = 0x00020000L;
const long WS_MAXIMIZEBOX = 0x00010000L;
long value = GetWindowLong(hwnd, GWL_STYLE);
Trace.TraceInformation("GetWindowLong value {0}", value.ToString());
long ret = SetWindowLong(hwnd, GWL_STYLE, (value & ~WS_MINIMIZEBOX & ~WS_MAXIMIZEBOX));
Trace.TraceInformation("SetWindowLong reg {0}", ret.ToString());
}
If the code above is for 32-bit, then on the SetWindowLong declaration the value parameter type should be int, not long. There is a possibility this may cause some inconsistent behavior.
For reference, here are the 32-bit signatures as defined internally in System.Windows.Forms:
[DllImport("user32.dll", CharSet = CharSet.Auto, EntryPoint = "SetWindowLong")]
public static extern IntPtr SetWindowLongPtr32(HandleRef hWnd, int nIndex, HandleRef dwNewLong);
[DllImport("user32.dll", CharSet = CharSet.Auto, EntryPoint = "GetWindowLong")]
public static extern IntPtr GetWindowLong32(HandleRef hWnd, int nIndex);
Also, using Spy++, you can verify what styles are on the IE window before and after you modify the style.

GetFocus - Win32api help

i am trying to grab the selected text from the open form on a users machine. Currently i have tried using GetFocus which is defined as
'[DllImport("user32.dll")]
static extern int GetFocus();'
In the api it says - Retrieves the handle to the window that has the keyboard focus, if the window is attached to the calling thread's message queue. Which explains why my app can grab the selected text from a window thats part of my app, but not one thats external, like a pdf for example.
What alternative win32 method is available for me to use that would fit this purpose?
Thanks.
edit: this is the attempt at the moment
[DllImport("user32.dll")]
static extern int GetFocus();
[DllImport("user32.dll")]
static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);
[DllImport("kernel32.dll")]
static extern uint GetCurrentThreadId();
[DllImport("user32.dll")]
static extern uint GetWindowThreadProcessId(int hWnd, int ProcessId);
[DllImport("user32.dll")]
static extern int GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
static extern int SendMessage(int hWnd, int Msg, int wParam, StringBuilder lParam);
// second overload of SendMessage
[DllImport("user32.dll")]
private static extern int SendMessage(IntPtr hWnd, uint Msg, out int wParam, out int lParam);
const int WM_SETTEXT = 12;
const int WM_GETTEXT = 13;
private static string PerformCopy()
{
try
{
//Wait 5 seconds to give us a chance to give focus to some edit window,
//notepad for example
System.Threading.Thread.Sleep(1000);
StringBuilder builder = new StringBuilder(500);
int foregroundWindowHandle = GetForegroundWindow();
uint remoteThreadId = GetWindowThreadProcessId(foregroundWindowHandle, 0);
uint currentThreadId = GetCurrentThreadId();
//AttachTrheadInput is needed so we can get the handle of a focused window in another app
AttachThreadInput(remoteThreadId, currentThreadId, true);
//Get the handle of a focused window
int focused = GetFocus();
//Now detach since we got the focused handle
AttachThreadInput(remoteThreadId, currentThreadId, false);
//Get the text from the active window into the stringbuilder
SendMessage(focused, WM_GETTEXT, builder.Capacity, builder);
return builder.ToString();
}
catch (System.Exception oException)
{
throw oException;
}
}
Check GetForegroundWindow.
I don't think you have much chance of succeeding with your current approach. I'm pretty sure there's no single general purpose API for getting hold of the current selection. I believe this because each application can implement text selection in its own way.
As an alternative solution you should consider using a clipboard listener. Listen for changes to the clipboard contents and whenever text is added you can suck it out of the clipboard and put it in your app's window.
I think this is a job for UI Automation (the API screen readers use). Here's a post that get's the selected text in C#.

How can I get functionality similar to Spy++ in my C# app?

I'm interested in working on a plugin for Keepass, the open-source password manager. Right now, Keepass currently detects what password to copy/paste for you based off of the window title. This prevents Keepass from detecting the current password you need for apps that don't actively update their window title based on the current site (Chrome for instance).
How can I walk through another processes window elements (buttons, labels, textbox) similar to how Spy++ works? When you run Spy++ you can hover over other programs windows and get all kinds of information about various properties concerning various controls (labels, textboxes, etc). Ideally, I'd like my Keepass plugin to enhance the current window detection by walking through the active window's elements in an effort to find a matching account to copy/paste the password.
How can I walk other processes window elements and be able to retrieve label and textbox values using C#?
I've being answering similar questions like this here: How can I detect if a thread has windows handles?. Like it states, the main idea is to enumerate through process windows and their child windows using EnumWindows and EnumChildWindows API calls to get window handles and then call GetWindowText or SendDlgItemMessage with WM_GETTEXT to get window text. I've modified code to make an example which should be doing what you need (sorry it's a bit long :). It iterates through processes and their windows and dumps window text into console.
static void Main(string[] args)
{
foreach (Process procesInfo in Process.GetProcesses())
{
Console.WriteLine("process {0} {1:x}", procesInfo.ProcessName, procesInfo.Id);
foreach (ProcessThread threadInfo in procesInfo.Threads)
{
// uncomment to dump thread handles
//Console.WriteLine("\tthread {0:x}", threadInfo.Id);
IntPtr[] windows = GetWindowHandlesForThread(threadInfo.Id);
if (windows != null && windows.Length > 0)
foreach (IntPtr hWnd in windows)
Console.WriteLine("\twindow {0:x} text:{1} caption:{2}",
hWnd.ToInt32(), GetText(hWnd), GetEditText(hWnd));
}
}
Console.ReadLine();
}
private static IntPtr[] GetWindowHandlesForThread(int threadHandle)
{
_results.Clear();
EnumWindows(WindowEnum, threadHandle);
return _results.ToArray();
}
// enum windows
private delegate int EnumWindowsProc(IntPtr hwnd, int lParam);
[DllImport("user32.Dll")]
private static extern int EnumWindows(EnumWindowsProc x, int y);
[DllImport("user32")]
private static extern bool EnumChildWindows(IntPtr window, EnumWindowsProc callback, int lParam);
[DllImport("user32.dll")]
public static extern int GetWindowThreadProcessId(IntPtr handle, out int processId);
private static List<IntPtr> _results = new List<IntPtr>();
private static int WindowEnum(IntPtr hWnd, int lParam)
{
int processID = 0;
int threadID = GetWindowThreadProcessId(hWnd, out processID);
if (threadID == lParam)
{
_results.Add(hWnd);
EnumChildWindows(hWnd, WindowEnum, threadID);
}
return 1;
}
// get window text
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern int GetWindowTextLength(IntPtr hWnd);
private static string GetText(IntPtr hWnd)
{
int length = GetWindowTextLength(hWnd);
StringBuilder sb = new StringBuilder(length + 1);
GetWindowText(hWnd, sb, sb.Capacity);
return sb.ToString();
}
// get richedit text
public const int GWL_ID = -12;
public const int WM_GETTEXT = 0x000D;
[DllImport("User32.dll")]
public static extern int GetWindowLong(IntPtr hWnd, int index);
[DllImport("User32.dll")]
public static extern IntPtr SendDlgItemMessage(IntPtr hWnd, int IDDlgItem, int uMsg, int nMaxCount, StringBuilder lpString);
[DllImport("User32.dll")]
public static extern IntPtr GetParent(IntPtr hWnd);
private static StringBuilder GetEditText(IntPtr hWnd)
{
Int32 dwID = GetWindowLong(hWnd, GWL_ID);
IntPtr hWndParent = GetParent(hWnd);
StringBuilder title = new StringBuilder(128);
SendDlgItemMessage(hWndParent, dwID, WM_GETTEXT, 128, title);
return title;
}
hope this helps, regards
Have a look at this article here which contains information about the Managed Spy and why the author wrote the tool.
You can use EnumWindows to find every top-level Chrome window and then call EnumChildWindows recursively (see Jeroen Wiert Pluimers' comment) to get every child of the main window. Alternatively, once you have the main Chrome window, you can use GetWindow to manually navigate the tree since you probably know what you're looking for (3rd child's children collection or something similar).
Once you find your window, you can use SendMessage with a WM_GETTEXT parameter to read the window's label.
You can use HWndSpy. Source code is here.
For the functionality of pointing to a window. You need to SetCapture() so that you get mouse messages that are outside of your window. Then use WindowFromPoint() to convert a mouse position to a Window. You will need to convert the moust position from client coordinates to window coordinates first.
If you try an call SetCapture() anywhere but on a mouse click message, you will probably be ignored. This is the reason that Spy++ makes you click on an Icon and drag and drop it on the window you want to point to.

Categories

Resources