Setting my C# form as a child to another application - c#

I'm currently developing a form application which works as an overlay to another program (Skype). Right now, I'm using TopMost = true, but that's a pretty bad solution.
I have a handle to the Skype window, as well as a handle to my own window. How do I make my program fulfill the following three statements:
1. It has to disappear if Skype is minimized
2. It has to appear above Skype
3. It has to appear behind any other application which is above Skype
Above and behind relates to z-order.
I'm currently using the SetWindowLong function, but I cant get the desired results.
[DllImport("user32.dll")]
public static extern int SetWindowLong(HandleRef hWnd, int nIndex, HandleRef dwNewLong);
SetWindowLong(
new HandleRef(child, child.Handle),
-8, // GWL_HWNDPARENT
new HandleRef(owner, owner.Handle));
For #1, my application continually checks if the dimensions of Skype has changed, so I could simply also check if the window is no longer visible. However, I'm completely at loss with #2 and #3.
Thanks in advance.
Kloar

Related

Getting a console window out of "select mode" to prevent a crash

In my C# application, I am trying to prevent a crash in my application, basically, I am using a Console window as a log display window. I already solved the "Close Button" issue by disabling the close window, and I show/hide the menu with Show and Hide calls, all of that is working just fine.
My final hurtle is if Text Selection is active and the window attempting to be hidden.
I either need to:
A. Kick the window out of select mode. (not sure how I would do this, since selection pauses all output.)
B. Disable the "Edit" menu in the same way I disabled the Close menu, in a hope that it would also disable the mouse selection, but I have yet to find any way to remove the "Edit" menu, and I am not even sure that would prevent mouse selection.
C. This seems the most obvious, disable mouse selection, and this is the one I have currently in my code, but it's not working, so I am not sure what I am missing.
The Code in Question:
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
....
[DllImport("Kernel32.dll", ExactSpelling = true)]
private static extern int SetConsoleMode(IntPtr hWnd, int wFlag);
....
public static void HideConsoleLog () {
if (handle != IntPtr.Zero) {
SetConsoleMode(handle, 0x0080); // ENABLE_EXTENDED_FLAGS 0x0080
ShowWindow(handle, (int)WinCntrlOpt.SW_HIDE);
LogVisible = false;
}
}
According to the Documentation:
ENABLE_EXTENDED_FLAGS 0x0080 Required to enable or disable extended
flags. See ENABLE_INSERT_MODE and ENABLE_QUICK_EDIT_MODE.
And...
ENABLE_QUICK_EDIT_MODE 0x0040 This flag enables the user to use the
mouse to select and edit text.
To enable this mode, use ENABLE_QUICK_EDIT_MODE |
ENABLE_EXTENDED_FLAGS. To disable this mode, use ENABLE_EXTENDED_FLAGS
without this flag.
So, it seems I am doing this correctly, and it does run, but it does not prevent mouse selection. I do know that not to long ago, Microsoft tinkered with Consoles, and I don't know if that's broke this or not.
There is a similar question on stack exchange, but that nether gives a working solution, and is in-fact the reverse to what I am trying to do and in C or C++. I can interpolate, but it's basically what I am already trying here.
It seems to be the same suggestion, use ENABLE_EXTENDED_FLAGS without any other flags to disable the option, and that's what I have. But it doesn't work.
So, I am either scratching at the wrong solution or am not doing something else correctly.
The effect is, while the console window is open, you can use the mouse to select text which automatically puts the console in that "select mode" that Microsoft's tinkering added. That's not a problem, but it's when it's left IN that mode, and you select "Show Log" (a check-marked toggle menu option in the main application window) The console window does indeed hide, but then the main window locks up and the application crashes. (my guess is because the window is blocked by that select mode.) It doesn't crash when the 'select mode' is not active.
I would also like to try this from the same documentation:
ENABLE_MOUSE_INPUT 0x0010 If the mouse pointer is within the borders
of the console window and the window has the keyboard focus, mouse
events generated by mouse movement and button presses are placed in
the input buffer. These events are discarded by ReadFile or
ReadConsole, even when this mode is enabled.
Problem is, it says:
When a console is created, all input modes except ENABLE_WINDOW_INPUT
are enabled by default.
So, how do I disable it?
I am fine with any solution that either kicks it out of select mode, or prevents it to begin with, and I have here what I have tried.
When the "Show Log" menu option is selected, the window is going to minimize.
Before the window minimizes, you have to check whether the user has selected any input to prevent the crash. You can check whether the user is selecting anything by using GetConsoleSelectionInfo.
The CONSOLE_SELECTION_INFO out parameter should be equal to 0x00, and if it's not, you need to process the selection. As the documentation from GetConsoleMode/SetConsoleMode shows, you either need to call ReadFile or ReadConsole to discard the selection event that might be going on.
When you've implemented this, it shouldn't crash anymore.

SetForegroundWindow method sometimes does not hide start menu

I have a Windows form with no border that is set to maximized in order to make it look "fullscreen". When I open my fullscreen form in my C# app I call the following code...
[DllImport("User32.dll")]
public static extern Int32 SetForegroundWindow(int hWnd);
With the handle I get from the Windows forms api by calling...
ScreenScrape.SetForegroundWindow(Handle.ToInt32());
When the "Shown" event is raised.
The only problem is sometimes I get the expected result (a fullscreen app with nothing in front of it) and sometimes I get this...
If i click anywhere on my Windows form and its embedded browser I see this...
Another developer suggested programmatically clicking at a known location Say 10,10 but that seems like a hack. Any idea what might be happening here?

Hide parent window, but show child window

I'm working on an application that should do the following on start-up:
Connect to an external application using COM (AutoCAD).
Send message to the application to run some DLL code (opens a window).
Hide AutoCAD's window, but keep the DLL's window visible.
I've successfully completed the first 2 steps, but the third is giving me some issues.
I do not know if it is possible to make a child window visible while it's parent is not visible. Every time that I make the child visible or make it the top most window, AutoCAD becomes visible as well.
My objective is to run my DLL code, but keep AutoCAD running in the background, completely invisible to my users. The DLL must be loaded, through AutoCAD, because it allows me to work with AutoCAD's .NET interface as opposed to COM.
In any case, I'm curious if what I'm trying to do is possible, perhaps through some Windows API calls or perhaps something in .NET.
PS: I'm unsure if this window relationship is really a parent-child one. I'm assuming it is though because my window belongs to the AutoCAD application instance due to the DLL loading.
Any help is greatly appreciated. Thanks! :)
EDIT:
DLL Code to create a window.
//CommandMethod is an AutoCAD attribute for entering into the DLL. This code is called
//when the user attempts the command "AUTOCADCOMMANDNAME" or can be done by simulating
//the command programmatically.
[CommandMethod("AUTOCADCOMMANDNAME", CommandFlags.Session)]
public void CommandEntry()
{
MainWindow mainWin = new MainWindow();
mainWin.ShowDialog();
}
Main Application Code
public static void Main()
{ //Use a utility class to create a connection to AutoCAD via COM
AcadApplication acadApp = ACUtil.GetAcadInstance(out createdNewInstance);
acadApp.Visible = false;
//Irrelevant code omitted...
acadApp.ActiveDocument.SendCommand("AUTOCADCOMMANDNAME");
acadApp.Quit(); //Exit AutoCAD application
//Note: doesn't quit until mainWin closes because of ShowDialog()
}
Can't be done. Parent windows control child window visibility.
Your best alternative is to make the DLL window a top-level window (but owned by the AutoCAD window).
Note that the DLL window will still be part of the AutoCAD thread.
What you want can be achieved, despite what others may think. You just need to think about the problem in a different way. Don't think about parent and child Windows... instead, think about a splash screen Window.
Typically, splash screens appear before the main application Window, but does that make them the parent? No, it doesn't. Normally, they'd be closed after the main Window has opened, but there is no reason why you couldn't hide it instead of closing it.
To find out how to do this in WPF, please refer to my answer from the How to open a child Window like a splash screen before MainWindow in WPF? question, here on Stack Overflow. Extending that answer a little bit, I should point out that you won't need to use a Timer. Instead of the code from the linked page, you could do something like this:
private void OpenMainWindow()
{
autoCadWindow.Visiblity = Visibility.Collapsed;
MainWindow mainWindow = new MainWindow();
mainWindow.Show();
}
Haha! I found it!
So, I ended up calling the SetWindowPos function in the Windows API and supplied the handle for AutoCAD window. I did this inside my main application:
[DllImport("User32.dll")]
static extern bool SetWindowPos(IntPtr hwnd, IntPtr hwndInsertAfter, int x, int y, int w, int h, uint flags);
public const int SWP_HIDEWINDOW = 0x0080;
public static void Main()
{
//...Setup AutoCAD...
//Change window size and hide it before calling to open mainWin inside the DLL.
SetWindowPos(new IntPtr(acadApp.HWND), new IntPtr(1), 0, 0, 0, 0, SWP_HIDEWINDOW);
//Display mainWin by entering the DLL.
acadApp.ActiveDocument.SendCommand("AUTOCADCOMMANDNAME");
//Terminate application as before...
}
Basically I'm telling the AutoCAD window to hide by modifying the HWND directly. I also set the dimensions to width=0 and height=0 which causes the window to take up the minimum size possible. Unfortunately, the window will flicker once, but for my purposes, that is negligible. If anyone can find a way to remove the flicker, that would be great! :)
EDIT: When using SetWindowPos, Windows tends to remember the values entered for the next time that application window is shown. This means that if not restored properly, then the next time the user opens AutoCAD manually, it will have the coordinates of 0,0 and the minimum width/height.
To change that behavior, it is necessary to obtain the window information. For my program, I used GetWindowRect obtain the original settings. Before closing my program, I restored those settings using SetWindowPos. See the code below for details:
First, import necessary WINAPI functions and structs:
[DllImport("User32.dll")]
static extern bool GetWindowRect(IntPtr hwnd, out RECT rect);
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
Obtain original settings before modifying window:
RECT originalRect;
GetWindowRect(new IntPtr(acadApp.HWND), out originalRect);
Modify the window to hide (and resize):
SetWindowPos(new IntPtr(acadApp.HWND), new IntPtr(1), 0, 0, 0, 0, SWP_HIDEWINDOW);
Restore original settings before quitting:
SetWindowPos(new IntPtr(acadApp.HWND), new IntPtr(1),
originalRect.Left,
originalRect.Top,
originalRect.Right - originalRect.Left,
originalRect.Bottom - originalRect.Top, 0);

how to find the window handle, of the control in application where mouse was clicked

I writing a C# application. I am looking a way to find a window handle of the controls in other applications by just giving the coordinates of the mouse click (or for that matter any coordinates).
Example: On my desktop, I have calculator application opened, notepad opened and some other 3rd party application running. Screen is covered partially by each of them. Now if I run my application and if I click at any location on the screen, I want to be able to find out the window handle of the control (button, textbox, label, tab, frame, etc.) under the mouse irrespective if it was clicked on a button in calculator, File menu in notepad, or some other control in the 3rd party application. It is similar to the functionality we get from Spy++.
BTW, this has already been done for you, sounds like all you need is to clone the repo then customize to your hearts content.
I don't think Global Hooks would be necessary.
You should be able to use any number of methods to get cursor position, hooking is just going to complicate things. For example, you can try the following:
using System;
using System.Windows;
using System.Windows.Input;
using System.Runtime.InteropServices;
namespace Namespace1
{
class Class1
{
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetCursorPos(ref Win32Point pt);
[StructLayout(LayoutKind.Sequential)]
internal struct Win32Point
{
public Int32 X;
public Int32 Y;
};
public static Point GetMousePosition()
{
Win32Point w32Mouse = new Win32Point();
GetCursorPos(ref w32Mouse);
return new Point(w32Mouse.X, w32Mouse.Y);
}
}
}
Then you just need a few Pinvoke signatures.
Namely, WindowFromPoint and EnumChildWindows.
Refer to "Enumerating Windows/Controls of another application from .Net".
Hope that helps.
Good luck.
Use Windows hook for mouse events (like oleksa said) then this PInvoke to get the foreground window : http://www.pinvoke.net/default.aspx/user32.getforegroundwindow
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
void yourFonction(){
[...]
IntPtr handleTopMostWindow = GetForegroundWindow();
}
you just need to call this method in your code to retrieve the window's foreground handle :
you have to set global Windows hook for mouse events. This will cause yours application to get mouse (or keyboard) clicks in foreign windows.
Please find this article on code project as sample C# wrapper on Windows API. Windows API functions are listed in the article too

C# program to paste text from clipbord to any point where mouse clicks

I want to paste text from my text box or rich text box in C# windows form application to out side of the form for example:
//on a button click event
textbox1.text=Clipboard.SetText(); // this will set text to clipboard
now I want when I click in address bar of Firefox or Google chrome to get the same text as I typed in my windows form application, as I can do it by CTRL+V but I want a C# program to do so for me and get text from clipboard when ever I click in address bar or rename a folder.
You could just turn on some windows disability settings, If dragging or pasting is too awkward.
If you really want to implement this, you need a global hook on the mouse so you can recieve mouse events from outside your application. See here or perhaps here.
Then you have a problem, do you want to paste anywhere or just in address bars. First you'll have to define what an address bar window is and work out if that is what has the focus.
Its a lot of effort and the behaviour is not especially desirable. If you really want this, please expand your question and improve its readability so that this post will be useful to future visitors.
This is completely untested, and I've never used these DLL calls in C#, but hopefully it will do the trick or at least come close...
public class Win32
{
public const uint WM_SETTEXT = 0x000c;
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
public static extern IntPtr SendMessage(HandleRef hWnd, uint Msg, IntPtr wParam, string lParam);
[DllImport("user32.dll")]
static extern IntPtr WindowFromPoint(int xPoint, int yPoint);
}
Elsewhere in the code...
IntPtr theHandle = WindowFromPoint(Cursor.Position.X, Cursor.Position.Y);
if (theHandle != null)
{
long res = Win32.SendMessage(theHandle, WM_SETTEXT, IntPtr.Zero, Clipboard.GetText());
}
Note: I'm not entirely sure that WindowFromPiont will get the handle of the child control (i.e. the actual textbox) of another window, rather than the handle of the window itself. You might have to find the child by the cursor position. Been a long time since I've done something like this, unfortunately.
Also, if you want to get a fancier with the acquisition of the window handle, see this question: getting active window name based on mouse clicks in c#

Categories

Resources