Send a Message to another textbox Application - c#

i try to send Messages from one Application to another Application..
I think the Code works perfectly and is not the problem, but the text is sending to the wrong textbox? I looked with Spy++, and i have two textboxes in Application 2, but for both textboxes i return the same Class from Spy++ ---> "WindowsForms10.EDIT.app.0.141b42a_r13_ad1"...
My Main Question is now, why have both textboxes the same "class" and how can i fix this? thx
private const int WM_SETTEXT = 0x000C;
[DllImport("user32.dll")]
private static extern IntPtr FindWindow(string lpClassName,string lpWindowName);
[DllImport("User32.dll")]
private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindows);
[DllImport("User32.dll")]
private static extern Int32 SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, StringBuilder lParam);
private void button4_Click(object sender, EventArgs e)
{
IntPtr hWnd = FindWindow(null, "Form1");
if (!hWnd.Equals(IntPtr.Zero))
{
IntPtr edithWnd = FindWindowEx(hWnd, IntPtr.Zero, "WindowsForms10.EDIT.app.0.141b42a_r13_ad1", null);
if (!edithWnd.Equals(IntPtr.Zero))
SendMessage(edithWnd, WM_SETTEXT, IntPtr.Zero, new StringBuilder("Hello World!"));
}
}
//Working Stuff...
IntPtr edithWnd = FindWindowEx(hWnd, IntPtr.Zero, "WindowsForms10.EDIT.app.0.141b42a_r12_ad1", null);
IntPtr nextHnd = edithWnd;
IntPtr editWnd = FindWindowEx(hWnd, nextHnd, "WindowsForms10.EDIT.app.0.141b42a_r12_ad1", null);
IntPtr nextHnd1 = editWnd;
IntPtr editWnd1 = FindWindowEx(hWnd, nextHnd1, "WindowsForms10.EDIT.app.0.141b42a_r12_ad1", null);
IntPtr nextHnd2 = editWnd1;
IntPtr editWnd2 = FindWindowEx(hWnd, nextHnd2, "WindowsForms10.EDIT.app.0.141b42a_r12_ad1", null);

Related

VSTO Word AddIn : Capture Paste operation by Ctrl+V

I am working on a VSTO Word AddIn project and I copy some paragraph from an external source (some other word doc) and want to paste it by using Ctrl + V in word addin.
After copying some texts and to paste the copied data into the word document, it should paste the copied data + I want to add some more custom functionalities like keeping the same format of the destination word doc. how to do that ?
To control the keyboard shortcuts for pasting some data into your document you can set up a keyboard hook using the SetWindowsHookEx Windows API function. For example:
private const int WH_KEYBOARD_LL = 13;
private const int WM_KEYDOWN = 0x0100;
private static IntPtr hookId = IntPtr.Zero;
private delegate IntPtr HookProcedure(int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, HookProcedure lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
hookId = SetHook(HookCallback);
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
UnhookWindowsHookEx(hookId);
}
private static IntPtr SetHook(HookProcedure procedure)
{
using (Process process = Process.GetCurrentProcess())
using (ProcessModule module = process.MainModule)
return SetWindowsHookEx(WH_KEYBOARD_LL, procedure, GetModuleHandle(module.ModuleName), 0);
}
private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
try
{
if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
{
int pointerCode = Marshal.ReadInt32(lParam);
string pressedKey = ((Keys)pointerCode).ToString();
//Do some sort of processing on key press
var thread = new Thread(() =>
{
if (Control.ModifierKeys != 0 && pointerCode == 48 && Keys.Shift != 0)
{
//
Microsoft.Office.Interop.Word.Selection currentSelection = Application.Selection;
if (currentSelection.Type == Word.WdSelectionType.wdSelectionIP)
{
currentSelection.TypeBackspace();
currentSelection.TypeText("()");
currentSelection.MoveLeft(1);
pointerCode = 0;
}
else
if (currentSelection.Type == Word.WdSelectionType.wdSelectionNormal)
{
currentSelection.TypeBackspace();
currentSelection.MoveLeft(1);
currentSelection.TypeText("()");
pointerCode = 0;
}
else
{
// Do nothing.
}
}
else
{
}
});
thread.Start();
}
}
catch
{
}
return CallNextHookEx(hookId, nCode, wParam, lParam);
}
To handle ribbon controls (including context menus) you can repurpose built-in controls. See Temporarily Repurpose Commands on the Office Fluent Ribbon for more information.
You can patch the GetClipboardData Windows API function using Detours and run any code you want in your new function.
Works for both Ctrl+V and paste from a popup menu.

Outlook security prompt auto approval

I'm writing a function that will allow users to import their e-mails from outlook in to corporate storage. But I've encounter a problem with security promt, and since we still have clients with office 2003 we can't disable it.
I'm trying to autoclick it with this code:
[DllImport("User32.dll")]
public static extern Int32 FindWindow(String lpClassName, String lpWindowName);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int SendMessage(int hWnd, int msg, int wParam, IntPtr lParam);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle);
private const int WM_LBUTTONDOWN = 0x201;
private const int WM_LBUTTONUP = 0x0202;
private void button1_Click(object sender, EventArgs e)
{
int hwnd = 0;
IntPtr hwndChild = IntPtr.Zero;
while (true)
{
hwnd = FindWindow(null, "Microsoft Outlook");
if (hwnd != 0)
{
hwndChild = FindWindowEx((IntPtr)hwnd, IntPtr.Zero, "Button", "Yes");
if (hwndChild != IntPtr.Zero)
{
SendMessage((int)hwndChild, WM_LBUTTONDOWN, 0, IntPtr.Zero);
SendMessage((int)hwndChild, WM_LBUTTONUP, 0, IntPtr.Zero);
}
else
{
//...
}
}
else
{
//...
}
hwnd = 0;
}
}
But when I'm trying to use that code I've encounter unexpected problem. Security promt will only disappear only when I'm actually performing mouse click no matter where even on some empty screen space. What is wrong with it?
Try out MAPILab's Advanced Security for Outlook. Should also work for Outlook 2003. This will let you give a permanent access for your application - a pop-up window will show only the first time you access Outlook items:
http://www.mapilab.com/outlook/security/
Advanced Security will have to be installed on each machine you run your app. It's free for noncommercial and commercial use.
You should try using SendKeys and send Y for Yes.

Interact with a form using handle C#

I am trying to automate a dynamically appearing dialogue box.
I need to pass text to it,s text field and then press a button over this.
What I have tried so far.
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);
IntPtr handle= FindWindowByCaption(System.IntPtr.Zero, "Caption Of File");
I am getting the handle of dialogue box correctly.
List<IntPtr> childWindows= GetChildWindows(handle);//To get the child controls in this dialogue box
Source
But when I try to cast it to control I get null.
foreach (IntPtr i in childWindows)
{
Control c = Control.FromHandle(i);
}
So can any body tell what is wrong.I am supposing that I shall cast handle to control and then interact with control properties(e.g: text).
I've been using code like this sucessfully for years to perform single sign on to an application that prompts the user for their username/pwd/domain. The only caution is you need to know the control structure of the dialog you're targeting, but this is easily accomplished with Spy++ and rarely changes. Of course you will need to modify this code for the control structure of your window.
[DllImport("user32.dll")]
static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter,
string lpszClass, string lpszWindow);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, uint msg, int wParam, string lParam);
[DllImport("User32.Dll")]
public static extern IntPtr PostMessage(IntPtr hWnd, uint msg, int wParam, int lParam);
private const uint WM_GETTEXTLENGTH = 0x000E;
private const uint WM_SETTEXT = 0x000C;
private const uint WM_GETTEXT = 0x000D;
private const uint BM_CLICK = 0x00F5;
private const uint WM_CLOSE = 0x0010;
enum GetWindow_Cmd : uint
{
GW_HWNDFIRST = 0,
GW_HWNDLAST = 1,
GW_HWNDNEXT = 2,
GW_HWNDPREV = 3,
GW_OWNER = 4,
GW_CHILD = 5,
GW_ENABLEDPOPUP = 6
}
var dialog FindWindow("optionalClassNameHere", "Log On"); //Get the handle of the window
var w3 = GetWindow(dialog , (uint)GetWindow_Cmd.GW_CHILD); //I use GetWindow to walk the window controls
var wUid = FindWindowEx(w3, IntPtr.Zero, "Edit", "");
var w4 = GetWindow(wUid, (uint)GetWindow_Cmd.GW_HWNDNEXT);
var wPwd = FindWindowEx(w4 , IntPtr.Zero, "Edit", "");
var wOK = FindWindowEx(w3, IntPtr.Zero, "Button", "OK");
SendMessage(wUid, WM_SETTEXT, 0, _WinDomain + "\\" + Username); //Send username to username edit control
SendMessage(wPwd, WM_SETTEXT, 0, Password); //Send password to password edit control
PostMessage(wOK, BM_CLICK, 0, 0); //Send left click(0x00f5) to OK button
Control.FromHandle can only work for controls in your process that are implemented by Control descendents. I'd guess this window is outside your process.
You need to use Win32 API methods to modify it.

Detect active window changed using C# without polling

How might one invoke a callback whenever the current active window changes. I've seen how it might be done using CBTProc. However, global events aren't easy to hook into with managed code. I'm interested in finding a way that doesn't require polling. I'd prefer an event driven approach.
Regards
Create a new windows forms project, add a textbox, make it multiline, and set the textbox Dock property to fill, name it Log and paste in the following code (you'll need to add System.Runtime.InteropServices to your usings)...
WinEventDelegate dele = null;
public Form1()
{
InitializeComponent();
dele = new WinEventDelegate(WinEventProc);
IntPtr m_hhook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, dele, 0, 0, WINEVENT_OUTOFCONTEXT);
}
delegate void WinEventDelegate(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);
[DllImport("user32.dll")]
static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmodWinEventProc, WinEventDelegate lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags);
private const uint WINEVENT_OUTOFCONTEXT = 0;
private const uint EVENT_SYSTEM_FOREGROUND = 3;
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
private string GetActiveWindowTitle()
{
const int nChars = 256;
IntPtr handle = IntPtr.Zero;
StringBuilder Buff = new StringBuilder(nChars);
handle = GetForegroundWindow();
if (GetWindowText(handle, Buff, nChars) > 0)
{
return Buff.ToString();
}
return null;
}
public void WinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
{
Log.Text += GetActiveWindowTitle() + "\r\n";
}
I know this thread is old, but for sake of future use:
when running the code you'll notice a crash after a while. This is caused from the line in the Form constructor:
public Form1()
{
InitializeComponent();
WinEventDelegate dele = new WinEventDelegate(WinEventProc);//<-causing ERROR
IntPtr m_hhook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, dele, 0, 0, WINEVENT_OUTOFCONTEXT);
}
Instead of the above make the following modification:
public Form1()
{
InitializeComponent();
dele = new WinEventDelegate(WinEventProc);
IntPtr m_hhook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, dele, 0, 0, WINEVENT_OUTOFCONTEXT);
}
WinEventDelegate dele = null;
..works now as expected!
You can use SetWinEventHook and listen for the EVENT_SYSTEM_FOREGROUND event. Use the WINEVENT_OUTOFCONTEXT flag to avoid the global-hook problem.

How to get ScrollBar positions of Notepad inside my form

I have a problem with getting scrollbar positions. Is it possible to get the scrollbar position of another process for example Notepad. I wrote small app where i tested and always get 0 0 as a position of scrollbars.
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int GetScrollPos(IntPtr hWnd, int nBar);
[DllImport("user32.dll")]
static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
[DllImport("user32.dll")]
static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool MoveWindow(IntPtr hwnd, int x, int y, int cx, int cy, bool repaint);
[DllImport("user32.dll")]
static extern IntPtr SetActiveWindow(IntPtr hWnd);
[DllImport("user32.dll", SetLastError = true)]
static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);
private void Form1_Load(object sender, EventArgs e)
{
this.SuspendLayout();
Process notepad = new Process();
ProcessStartInfo psi = new ProcessStartInfo(#"c:\list1.txt");
psi.WindowStyle = ProcessWindowStyle.Normal;
notepad.StartInfo = psi;
notepad.Start();
this.ResumeLayout();
notepad.WaitForInputIdle(3000);
IntPtr old = SetParent(notepad.MainWindowHandle, this.Handle);
SetWindowLong(notepad.MainWindowHandle, GWL_STYLE, WS_VISIBLE + WS_MAXIMIZE);
MoveWindow(notepad.MainWindowHandle, 100, 100, 400, 400, true);
SetActiveWindow(notepad.MainWindowHandle);
SwitchToThisWindow(notepad.MainWindowHandle, true);
}
I have button which send PGDN event to notepad and it works great but after pgdn event position of scrollbar also is 0 0
private void PGDN_Click(object sender, EventArgs e)
{
Process[] procs = Process.GetProcessesByName("Notepad");
IntPtr hwnd = procs[0].MainWindowHandle;
SetActiveWindow(hwnd);
SwitchToThisWindow(hwnd, true);
Thread.Sleep(2000);
SendKeys.SendWait("{PGDN}");
Thread.Sleep(2000);
label1.Text = "OK";
label1.Text = "";
label1.Text = HScrollPos().ToString() + " " + VScrollPos().ToString(); }
Here are the HScrollPos and VScrollPos functions :
public int VScrollPos()
{
Process[] procs = Process.GetProcessesByName("Notepad");
IntPtr hwnd = procs[0].MainWindowHandle;
if (procs.Length != 0)
{
return GetScrollPos(hwnd , SB_VERT);
}
else
{
MessageBox.Show("Notepad Nor Running");
return 0;
}
}
public int HScrollPos()
{
Process[] procs = Process.GetProcessesByName("Notepad");
IntPtr hwnd = procs[0].MainWindowHandle;
if (procs.Length != 0)
{
return GetScrollPos(hwnd , SB_HORZ);
}
else
{
MessageBox.Show("Notepad Nor Running");
return 0;
}
}
Maybe there is another way to get Scrollbar Position of another process/window in windows? Please Help. Thx for granted.
And here is the Working Code based on Answer. Thx
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
private void button4_Click(object sender, EventArgs e)
{
string lpszParentClass = "Notepad";
string lpszParentWindow = "Untitled - Notepad";
string lpszClass = "Edit";
IntPtr ParenthWnd = new IntPtr(0);
IntPtr hWnd = new IntPtr(0);
ParenthWnd = FindWindow(lpszParentClass, lpszParentWindow);
if (ParenthWnd.Equals(IntPtr.Zero))
MessageBox.Show("Notepad Not Running");
else
{
hWnd = FindWindowEx(ParenthWnd, hWnd, lpszClass, "");
if (hWnd.Equals(IntPtr.Zero))
MessageBox.Show("Notepad doesn't have an edit component ?");
else
{
MessageBox.Show("Notepad Window: " + ParenthWnd.ToString());
MessageBox.Show("Edit Control: " + hWnd.ToString());
}
}
SetActiveWindow(ParenthWnd);
label5.Text = GetScrollPos(hWnd, SB_VERT) + " " + GetScrollPos(hWnd, SB_HORZ);
}
I suspect the problem is that you are using the main window handle, you should be using the handle of the Edit control, which is a child of the main window.
Using the main window hwnd you can enumrate the child windows to find the hWnd of the edit control and then use that hWnd in your call to get the scroll bar position.
SendKeys is working because it is sending the key stroke to the window that has input focus which in this case is the Edit control.
Here is an answer to a question I provided sometime back that will help with the interop for EnumChildWindows if you need, there is a lot more there but it might help.

Categories