I've already checked out:
SetWindowPos not working on Form.Show()
Launch an application and send it to second monitor?
However, none of these solutions seem to work for me. I want to open an external program on a different monitor.
This is my current code:
public const int SWP_NOSIZE = 0x0001;
public const int SWP_NOZORDER = 0x0004;
public const int SWP_SHOWWINDOW = 0x0040;
[DllImport("user32.dll", SetLastError = true)]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);
[DllImport("user32.dll")]
public static extern bool UpdateWindow(IntPtr hWnd);
Process application = new Process();
application.StartInfo.UseShellExecute = false;
application.StartInfo.FileName = ".......";
if (application.Start())
{
Rectangle monitor = Screen.AllScreens[1].Bounds; // for monitor no 2
SetWindowPos(
application.MainWindowHandle,
IntPtr.Zero,
monitor.Left,
monitor.Top,
monitor.Width,
monitor.Height,
SWP_NOZORDER | SWP_NOSIZE | SWP_SHOWWINDOW);
UpdateWindow(application.MainWindowHandle); // tried even with application.Handle
}
First of all, you don't need UpdateWindow, calling SetWindowPos is probably enough. You just need to make sure that the window handle is created (because the process is being started). Simply add the following line before calling SetWindowPos:
application.WaitForInputIdle();
If WaitForInputIdle() doesn't work for you, you might try something like:
while (application.MainWindowHandle == IntPtr.Zero)
{
await Task.Delay(100);
}
The following code works fine for me:
Process application = new Process();
application.StartInfo.UseShellExecute = false;
application.StartInfo.FileName = "notepad.exe";
if (application.Start())
{
application.WaitForInputIdle();
/* Optional
while (application.MainWindowHandle == IntPtr.Zero)
{
await Task.Delay(100);
} */
Rectangle monitor = Screen.AllScreens[1].Bounds; // for monitor no 2
SetWindowPos(
application.MainWindowHandle,
IntPtr.Zero,
monitor.Left,
monitor.Top,
monitor.Width,
monitor.Height,
SWP_NOZORDER | SWP_NOSIZE | SWP_SHOWWINDOW);
}
Note that this will only set the position of the window, not its size though. If you want the size to be changed as well, you'll need to remove the SWP_NOSIZE flag.
Related
First of all, please understand that I am not good at English so I am not good at choosing or write sentence or word.
I am having an issue with C# TopMost not working.
calling method is at Called C# Application From VB6.
according to each specific situation show different from each other Form.
All forms have the following code:
// Define
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
private const UInt32 SWP_NOSIZE = 0x0001;
private const UInt32 SWP_NOMOVE = 0x0002;
private const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;
// All forms have the following code:
SetWindowPos(f.Handle, HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);
Commom.User32.AllowSetForegroundWindow((uint)Process.GetCurrentProcess().Id);
Commom.User32.SetForegroundWindow(h);
Commom.User32.ShowWindow(h, 1);
f.BringToFront();
f.TopLevel = true;
f.TopMost = true;
f.Focus();
// f is Form, h is Handle
Despite the above, it's TopMost not working.
I want you to help me if you know the problem or if you can help me.
Have a good day.
I have a MS Word Application Add-in written with VSTO. It contains a button used to create new Letter documents. When pressed a document is instantiated, a WPF dialog is displayed to capture information and then the information is inserted into the document.
On rare occasions, the WPF dialog slips behind MS Word. I then have to kill the Winword.exe process because the dialog is Modal.
I use the following code for my WPF dialog. The OfficeDialog sub class is used to make the dialog look like a MS-Word dialog.
var view = new LetterDetailsView(ViewModel);
view.ShowDialog();
public class OfficeDialog : Window
{
[DllImport("user32.dll")]
static extern int GetWindowLong(IntPtr hwnd, int index);
[DllImport("user32.dll")]
static extern int SetWindowLong(IntPtr hwnd, int index, int newStyle);
[DllImport("user32.dll")]
static extern bool SetWindowPos(IntPtr hwnd, IntPtr hwndInsertAfter, int x, int y, int width, int height, uint flags);
[DllImport("user32.dll")]
static extern IntPtr SendMessage(IntPtr hwnd, uint msg, IntPtr wParam, IntPtr lParam);
const int GWL_EXSTYLE = -20;
const int WS_EX_DLGMODALFRAME = 0x0001;
const int SWP_NOSIZE = 0x0001;
const int SWP_NOMOVE = 0x0002;
const int SWP_NOZORDER = 0x0004;
const int SWP_FRAMECHANGED = 0x0020;
const uint WM_SETICON = 0x0080;
const int ICON_SMALL = 0;
const int ICON_BIG = 1;
public OfficeDialog()
{
this.ShowInTaskbar = false;
}
public new void ShowDialog()
{
try
{
var helper = new WindowInteropHelper(this);
using (Process currentProcess = Process.GetCurrentProcess())
helper.Owner = currentProcess.MainWindowHandle;
base.ShowDialog();
}
catch (System.ComponentModel.Win32Exception ex)
{
Message.LogWarning(ex);
var helper = new WindowInteropHelper(this);
using (Process currentProcess = Process.GetCurrentProcess())
helper.Owner = currentProcess.MainWindowHandle;
base.ShowDialog();
}
}
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
RemoveIcon(this);
HideMinimizeAndMaximizeButtons(this);
}
public static void HideMinimizeAndMaximizeButtons(Window window)
{
const int GWL_STYLE = -16;
IntPtr hwnd = new WindowInteropHelper(window).Handle;
long value = GetWindowLong(hwnd, GWL_STYLE);
SetWindowLong(hwnd, GWL_STYLE, (int)(value & -131073 & -65537));
}
public static void RemoveIcon(Window w)
{
// Get this window's handle
IntPtr hwnd = new WindowInteropHelper(w).Handle;
// Change the extended window style to not show a window icon
int extendedStyle = OfficeDialog.GetWindowLong(hwnd, GWL_EXSTYLE);
OfficeDialog.SetWindowLong(hwnd, GWL_EXSTYLE, extendedStyle | WS_EX_DLGMODALFRAME);
// reset the icon, both calls important
OfficeDialog.SendMessage(hwnd, WM_SETICON, (IntPtr)ICON_SMALL, IntPtr.Zero);
OfficeDialog.SendMessage(hwnd, WM_SETICON, (IntPtr)ICON_BIG, IntPtr.Zero);
// Update the window's non-client area to reflect the changes
OfficeDialog.SetWindowPos(hwnd, IntPtr.Zero, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
}
static void SetCentering(Window win, IntPtr ownerHandle)
{
bool isWindow = IsWindow(ownerHandle);
if (!isWindow) //Don't try and centre the window if the ownerHandle is invalid. To resolve issue with invalid window handle error
{
//Message.LogInfo(string.Format("ownerHandle IsWindow: {0}", isWindow));
return;
}
//Show in center of owner if win form.
if (ownerHandle.ToInt32() != 0)
{
var helper = new WindowInteropHelper(win);
helper.Owner = ownerHandle;
win.WindowStartupLocation = WindowStartupLocation.CenterOwner;
}
else
win.WindowStartupLocation = WindowStartupLocation.CenterOwner;
}
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool IsWindow(IntPtr hWnd);
}
A modal dialog not being on top is the result of an incorrectly set owner. You already set the owner to the MainWindowHandle of the current process; however, in particular with multiple Word documents open, this might not be what you want.
I'd suggest to rely on the following property (introduced with Word 2013):
document.ActiveWindow.HWnd;
Apart from that there should not be the need to kill the Word process. It should be sufficient to minimize all windows (e.g. by pressing Windows Key + M)
I'm trying to embed the osk in a wpf window or a user control and I've found the code below and it's working for notepad but for tabtip.exe, it's saying that it doesn't have a graphical interface??
WaitForInputIdle failed. This could be because the process does not have a graphical interface.
I tried letting it sleep for awhile instead of calling waitForInputIdle method but it throws another exception:
Process has exited, so the requested information is not available.
But in my task manager, I can still see TabTip.exe running.
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private System.Windows.Forms.Panel _panel;
private Process _process;
public MainWindow()
{
InitializeComponent();
_panel = new System.Windows.Forms.Panel();
windowsFormsHost1.Child = _panel;
}
[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32")]
private static extern IntPtr SetParent(IntPtr hWnd, IntPtr hWndParent);
[DllImport("user32")]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);
private const int SWP_NOZORDER = 0x0004;
private const int SWP_NOACTIVATE = 0x0010;
private const int GWL_STYLE = -16;
private const int WS_CAPTION = 0x00C00000;
private const int WS_THICKFRAME = 0x00040000;
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
base.OnClosing(e);
if (_process != null)
{
_process.Refresh();
_process.Close();
}
}
private void ResizeEmbeddedApp()
{
if (_process == null)
return;
SetWindowPos(_process.MainWindowHandle, IntPtr.Zero, 0, 0, (int)_panel.ClientSize.Width, (int)_panel.ClientSize.Height, SWP_NOZORDER | SWP_NOACTIVATE);
}
protected override Size MeasureOverride(Size availableSize)
{
Size size = base.MeasureOverride(availableSize);
ResizeEmbeddedApp();
return size;
}
private void button1_Click_1(object sender, RoutedEventArgs e)
{
button1.Visibility = Visibility.Hidden;
ProcessStartInfo psi = new ProcessStartInfo("C:\\Program Files\\Common Files\\microsoft shared\\ink\\TabTip.exe");
_process = Process.Start(psi);
Thread.Sleep(500);
//_process.WaitForInputIdle();
SetParent(_process.MainWindowHandle, _panel.Handle);
// remove control box
int style = GetWindowLong(_process.MainWindowHandle, GWL_STYLE);
style = style & ~WS_CAPTION & ~WS_THICKFRAME;
SetWindowLong(_process.MainWindowHandle, GWL_STYLE, style);
// resize embedded application & refresh
ResizeEmbeddedApp();
}
}
}
Edit: Inspired by rene's comment, I've tried to obtain the window ptr as below and used spy++ to verify that the address that FindWindow gives is pointing to the correct window, but it's still not moving:
IntPtr KeyboardWnd = FindWindow("IPTip_Main_Window", null);
int style = GetWindowLong(KeyboardWnd, GWL_STYLE);
style = style & ~WS_CAPTION & ~WS_THICKFRAME;
SetWindowLong(KeyboardWnd, GWL_STYLE, style);
SetWindowPos(KeyboardWnd, IntPtr.Zero, 0, 0, (int)_panel.ClientSize.Width, (int)_panel.ClientSize.Height, SWP_NOZORDER | SWP_NOACTIVATE);
Edit 2: My first thought was that tab tip couldn't be resized, but then I noticed a behavior when I try to move the window across two different screen, it'll resize to fit the screen size, so I'm sure there must be a way to resize, so I started spy++(x64) to check :
Edit 3: after tinkering abit with user32 api and no progress, I've tried to use a memory scanner to scan for the x and y position of tabtip and change it, however, it's not refreshing until a repaint is triggered, I'm wondering the feasibility going down that path.
Can you try to run your handle code in STA thread? I had a similar issue with native window, which I had resolved using STA thread.
var thread = new Thread(() => {
// Your code here
});
thread.TrySetApartmentState(ApartmentState.STA);
thread.Start();
I had a similar problem, and the reason I had it was that I started a program that needed to be run by an administrator with a non-administrative program, and it would pop up with WaitForInputIdle failed. This could be because the process does not have a graphical interface, so I assume you try starting your program with an administrator
I need Form2 to be always on top of every single window - including games in fullscreen. This always works with windowed-mode applications, but it sometimes won't appear topmost when another app is in fullscreen mode. (Games, OpenGL, direct)
How can I fix this?
Form1:
Overlay overlayui = new Overlay();
overlayui.TopMost = true; // I have tried setting TopMost to false, same result.
overlayui.Show();
Form2:
Settings in WinForms designed view:
FormBorderStyle = none
ControlBox = false
ShowIcon = false
ShowInTaskBar = false
TopMost = false
I've implemented this piece of code used in similar issues:
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
const UInt32 SWP_NOSIZE = 0x0001;
const UInt32 SWP_NOMOVE = 0x0002;
const UInt32 SWP_SHOWWINDOW = 0x0040;
public Overlay()
{
InitializeComponent();
this.Bounds = Screen.PrimaryScreen.Bounds;
}
I then implemented a timer (interval 10 ms):
private void timer1_Tick(object sender, EventArgs e)
{
SetWindowPos(this.Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
}
internal class MessagesFilter : IMessageFilter
{
private readonly IntPtr ControlHandler;
private const int WM_KEYUP = 0x0101;
public MessagesFilter(IntPtr ControlHandler)
{
this.ControlHandler = ControlHandler;
}
#region IMessageFilter Members
public bool PreFilterMessage(ref Message m)
{
// TODO: Add MessagesFilter.PreFilterMessage implementation
if (m.Msg == WM_KEYUP)
{
if (m.HWnd == ControlHandler)
{
Keys k = ((Keys)((int)m.WParam));
if (k == Keys.Enter)
return true;
}
}
return false;
}
#endregion
}
EDIT:
I've implemented new timer :
SetWindowPos(processNOtopmost, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE )
So first time brings to top my app, and second one is removing from topmost external app.
Still same problem, sometimes it works, sometimes it doesn't.
You want to set:
TopMost = true
As far as i'm aware though this only makes it the topmost Window for you Application.
You have no control over other applications unless you prevent loss of Focus completely (not advised)
And besides most of the applications that are 'Stealing' focus from you will be DirectX and get priority on the GPU.
how to change the window style of a form outside your app?hard question?
i am actually trying to move a form witch is topmost and has no border.
i have the handle(hWnd) of the window.
i can write thousands of lines of code if guaranteed to work.
Assuming that this window could be from any app produced from any kind of Win32-based runtime, it looks like you'll have to resort to p/invoke of the core Win32 apis for window operations.
For example, you could use SetWindowPos, which can be imported from user32.dll. It's signature is this:
BOOL SetWindowPos(HWND hWnd,
HWND hWndInsertAfter,
int X,
int Y,
int cx,
int cy,
UINT uFlags
);
I'm not going to assume that you've done a p/invoke import before, so let's go from the top. Let's just bash out a windows forms app:
1) Create a windows forms app and then add these declarations to the Form1 class:
/* hWndInsertAfter constants. Lifted from WinUser.h,
* lines 4189 onwards depending on Platform SDK version */
public static IntPtr HWND_TOP = (IntPtr)0;
public static IntPtr HWND_BOTTOM = (IntPtr)1;
public static IntPtr HWND_TOPMOST = (IntPtr)(-1);
public static IntPtr HWND_NOTOPMOST = (IntPtr)(-2);
/* uFlags constants. Lifted again from WinUser.h,
* lines 4168 onwards depending on Platform SDK version */
/* these can be |'d together to combine behaviours */
public const int SWP_NOSIZE = 0x0001;
public const int SWP_NOMOVE = 0x0002;
public const int SWP_NOZORDER = 0x0004;
public const int SWP_NOREDRAW = 0x0008;
public const int SWP_NOACTIVATE = 0x0010;
public const int SWP_FRAMECHANGED = 0x0020;
public const int SWP_SHOWWINDOW = 0x0040;
public const int SWP_HIDEWINDOW = 0x0080;
public const int SWP_NOCOPYBITS = 0x0100;
public const int SWP_NOOWNERZORDER = 0x0200; /* Don't do owner Z ordering */
public const int SWP_NOSENDCHANGING = 0x0400; /* Don't send WM_WINDOWPOSCHANGING */
public const int SWP_DRAWFRAME = SWP_FRAMECHANGED;
public const int SWP_NOREPOSITION = SWP_NOOWNERZORDER;
public const int SWP_DEFERERASE = 0x2000;
public const int SWP_ASYNCWINDOWPOS = 0x4000;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int SetWindowsPos(IntPtr hWnd,
IntPtr hWndInsertAfter,
int x,
int y,
int cx,
int cy,
UInt32 uFlags);
The annoying thing with p/invoke of Win32 windows methods is that you then have to start importing various numeric constants etc that Win32 uses - hence all the gumph beforehand.
Refer to the MSDN link for the SetWindowPos method for an explanation of what they do.
2) Add a button to the form called cmdMakeHidden and then write the handler as follows:
private void cmdMakeHidden_Click(object sender, EventArgs e)
{
//also causes the icon in the start bar to disappear
//SWP_HIDEWINDOW is the 'kill -9' of the windows world without actually killing!
SetWindowPos(this.Handle, HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_HIDEWINDOW);
}
Replace the 'this.Handle' with the window handle of your choice to hide that window.
This method is actually used to apply multiple changes at once, hence the need to use some of the SWP_NO* options. For example, you should specify SWP_NOSIZE otherwise passing 0 for cx and cy will cause the window to shrink to zero width and height at the same time.
To demonstrate moving a window, add another button your form called cmdMove and then write the click handler as follows:
private void cmdMove_Click(object sender, EventArgs e)
{
SetWindowPos(this.Handle, HWND_TOP, 100, 100, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOREPOSITION);
}
This code moves your form to 100,100 whenever you hit the button.
Again, replace the this.Handle as you see fit. HWND_TOP here is completely optional, since reordering has been disabled with the SWP_NOZORDER and SWP_NOREPOSITION flags.
Hope this helps get you on the right track!