open a page in IE using c# - c#

I'm opening a webpage in IE using c#
Code:
Process.Start("IExplore.exe", "www.northwindtraders.com");
But, how can I resize the page with the following characteritics: toolbar=no, location=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width='622', height='582'

For that level of fine grained control which I do not believe is available from the command line add a reference (COM) to Microsoft Internet Controls and then you can:
var IE = new SHDocVw.InternetExplorer();
object URL = "http://www.northwindtraders.com";
IE.ToolBar = 0;
IE.StatusBar = false;
IE.MenuBar = false;
IE.Width = 622;
IE.Height = 582;
IE.Visible = true;
IE.Navigate2(ref URL);

These are the features for opening Internet Explorer from Command Shell:
http://msdn.microsoft.com/en-us/library/hh826025(v=vs.85).aspx

You need to use the StartInfo property to set some startup parameters.
Check this link for what options are available.

You can do it without a reference to SHDocVw, by using the COM-object directly:
const int FormWidth = 800;
const int FormHeight = 600;
// http://www.c-sharpcorner.com/forums/thread/51998/opening-a-browser-and-hiding-the-address-bar-help.aspx
// http://weblog.west-wind.com/posts/2005/Apr/29/Previewing-HTML-with-InternetExplorerApplication-in-C
// http://social.msdn.microsoft.com/Forums/vstudio/en-US/ab6969c7-0a34-4d88-9a74-b66888d3d88f/ie-automation-navigating-the-soup
// http://superuser.com/questions/459775/how-can-i-launch-a-browser-with-no-window-frame-or-tabs-address-bar
public void OpenBrowserWindow(string strURL)
{
// System.Diagnostics.Process.Start(strURL)
// For Internet Explorer you can use -k (kiosk mode):
// iexplore.exe -k http://www.google.com/
// Internet Explorer Command-Line Options
// http://msdn.microsoft.com/en-us/library/ie/hh826025(v=vs.85).aspx
// Starts Internet Explorer in kiosk mode. The browser opens in a maximized window that does not display the address bar,
// the navigation buttons, or the status bar.
System.Drawing.Rectangle rect = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
// http://stackoverflow.com/questions/5049122/capture-the-screen-shot-using-net
int posX = rect.Width - FormWidth;
int posY = rect.Height - FormHeight;
posX = Convert.ToInt32 (posX / 2.0);
posY = Convert.ToInt32 (posY / 2.0);
posX = Math.Max (posX, 0);
posY = Math.Max (posY, 0);
System.Type oType = System.Type.GetTypeFromProgID ("InternetExplorer.Application");
object o = System.Activator.CreateInstance (oType);
o.GetType ().InvokeMember ("MenuBar", System.Reflection.BindingFlags.SetProperty, null, o, new object[] { 0 });
o.GetType ().InvokeMember ("ToolBar", System.Reflection.BindingFlags.SetProperty, null, o, new object[] { 0 });
o.GetType ().InvokeMember ("StatusBar", System.Reflection.BindingFlags.SetProperty, null, o, new object[] { 0 });
o.GetType ().InvokeMember ("AddressBar", System.Reflection.BindingFlags.SetProperty, null, o, new object[] { 0 });
o.GetType ().InvokeMember ("Visible", System.Reflection.BindingFlags.SetProperty, null, o, new object[] { true });
o.GetType ().InvokeMember ("Top", System.Reflection.BindingFlags.SetProperty, null, o, new object[] { posY });
o.GetType ().InvokeMember ("Left", System.Reflection.BindingFlags.SetProperty, null, o, new object[] { posX });
o.GetType ().InvokeMember ("Width", System.Reflection.BindingFlags.SetProperty, null, o, new object[] { FormWidth });
o.GetType ().InvokeMember ("Height", System.Reflection.BindingFlags.SetProperty, null, o, new object[] { FormHeight });
o.GetType ().InvokeMember ("Navigate", System.Reflection.BindingFlags.InvokeMethod, null, o, new object[] { strURL });
try
{
object ohwnd = o.GetType ().InvokeMember ("hwnd", System.Reflection.BindingFlags.GetProperty, null, o, null);
System.IntPtr IEHwnd = (System.IntPtr)ohwnd;
// NativeMethods.SetForegroundWindow (IEHwnd);
NativeMethods.ShowWindow(IEHwnd, NativeMethods.WindowShowStyle.ShowMaximized);
} catch (Exception ex) {
}
} // OpenBrowserWindow
public class NativeMethods
{
[System.Runtime.InteropServices.DllImport("user32.dll")]
[return: System.Runtime.InteropServices.MarshalAs(
System.Runtime.InteropServices.UnmanagedType.Bool)]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[System.Runtime.InteropServices.DllImport ("user32.dll")]
[return: System.Runtime.InteropServices.MarshalAs(
System.Runtime.InteropServices.UnmanagedType.Bool)]
public static extern bool ShowWindow(IntPtr hwnd, WindowShowStyle nCmdShow);
/// <summary>Enumeration of the different ways of showing a window using
/// ShowWindow</summary>
public enum WindowShowStyle : int
{
/// <summary>Hides the window and activates another window.</summary>
/// <remarks>See SW_HIDE</remarks>
Hide = 0,
/// <summary>Activates and displays a window. If the window is minimized
/// or maximized, the system restores it to its original size and
/// position. An application should specify this flag when displaying
/// the window for the first time.</summary>
/// <remarks>See SW_SHOWNORMAL</remarks>
ShowNormal = 1,
/// <summary>Activates the window and displays it as a minimized window.</summary>
/// <remarks>See SW_SHOWMINIMIZED</remarks>
ShowMinimized = 2,
/// <summary>Activates the window and displays it as a maximized window.</summary>
/// <remarks>See SW_SHOWMAXIMIZED</remarks>
ShowMaximized = 3,
/// <summary>Maximizes the specified window.</summary>
/// <remarks>See SW_MAXIMIZE</remarks>
Maximize = 3,
/// <summary>Displays a window in its most recent size and position.
/// This value is similar to "ShowNormal", except the window is not
/// actived.</summary>
/// <remarks>See SW_SHOWNOACTIVATE</remarks>
ShowNormalNoActivate = 4,
/// <summary>Activates the window and displays it in its current size
/// and position.</summary>
/// <remarks>See SW_SHOW</remarks>
Show = 5,
/// <summary>Minimizes the specified window and activates the next
/// top-level window in the Z order.</summary>
/// <remarks>See SW_MINIMIZE</remarks>
Minimize = 6,
/// <summary>Displays the window as a minimized window. This value is
/// similar to "ShowMinimized", except the window is not activated.</summary>
/// <remarks>See SW_SHOWMINNOACTIVE</remarks>
ShowMinNoActivate = 7,
/// <summary>Displays the window in its current size and position. This
/// value is similar to "Show", except the window is not activated.</summary>
/// <remarks>See SW_SHOWNA</remarks>
ShowNoActivate = 8,
/// <summary>Activates and displays the window. If the window is
/// minimized or maximized, the system restores it to its original size
/// and position. An application should specify this flag when restoring
/// a minimized window.</summary>
/// <remarks>See SW_RESTORE</remarks>
Restore = 9,
/// <summary>Sets the show state based on the SW_ value specified in the
/// STARTUPINFO structure passed to the CreateProcess function by the
/// program that started the application.</summary>
/// <remarks>See SW_SHOWDEFAULT</remarks>
ShowDefault = 10,
/// <summary>Windows 2000/XP: Minimizes a window, even if the thread
/// that owns the window is hung. This flag should only be used when
/// minimizing windows from a different thread.</summary>
/// <remarks>See SW_FORCEMINIMIZE</remarks>
ForceMinimized = 11
}
}
You can also use VirtualScreen
System.Windows.Forms.SystemInformation.VirtualScreen.Width;
System.Windows.Forms.SystemInformation.VirtualScreen.Height;
instead of PrimaryScreen

Another way is to use window messages this is thrown together from PInvoke.net
void Main()
{
Process p = Process.Start(
#"C:\Program Files (x86)\Internet Explorer\iexplore.exe" , "www.google.com" );
while(p.MainWindowHandle == IntPtr.Zero )
{
Thread.Sleep(100);
p.Refresh();
}
SetWindowPos( p.MainWindowHandle , IntPtr.Zero , 100 , 100, 800 ,400 , SetWindowPosFlags.ShowWindow );
}
// Define other methods and classes here
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, SetWindowPosFlags uFlags);
static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);
static readonly IntPtr HWND_TOP = new IntPtr(0);
static readonly IntPtr HWND_BOTTOM = new IntPtr(1);
/// <summary>
/// Window handles (HWND) used for hWndInsertAfter
/// </summary>
public static class HWND
{
public static IntPtr
NoTopMost = new IntPtr(-2),
TopMost = new IntPtr(-1),
Top = new IntPtr(0),
Bottom = new IntPtr(1);
}
/// <summary>
/// SetWindowPos Flags
/// </summary>
public static class SWP
{
public static readonly int
NOSIZE = 0x0001,
NOMOVE = 0x0002,
NOZORDER = 0x0004,
NOREDRAW = 0x0008,
NOACTIVATE = 0x0010,
DRAWFRAME = 0x0020,
FRAMECHANGED = 0x0020,
SHOWWINDOW = 0x0040,
HIDEWINDOW = 0x0080,
NOCOPYBITS = 0x0100,
NOOWNERZORDER = 0x0200,
NOREPOSITION = 0x0200,
NOSENDCHANGING = 0x0400,
DEFERERASE = 0x2000,
ASYNCWINDOWPOS = 0x4000;
}
[Flags()]
private enum SetWindowPosFlags : uint
{
/// <summary>If the calling thread and the thread that owns the window are attached to different input queues,
/// the system posts the request to the thread that owns the window. This prevents the calling thread from
/// blocking its execution while other threads process the request.</summary>
/// <remarks>SWP_ASYNCWINDOWPOS</remarks>
AsynchronousWindowPosition = 0x4000,
/// <summary>Prevents generation of the WM_SYNCPAINT message.</summary>
/// <remarks>SWP_DEFERERASE</remarks>
DeferErase = 0x2000,
/// <summary>Draws a frame (defined in the window's class description) around the window.</summary>
/// <remarks>SWP_DRAWFRAME</remarks>
DrawFrame = 0x0020,
/// <summary>Applies new frame styles set using the SetWindowLong function. Sends a WM_NCCALCSIZE message to
/// the window, even if the window's size is not being changed. If this flag is not specified, WM_NCCALCSIZE
/// is sent only when the window's size is being changed.</summary>
/// <remarks>SWP_FRAMECHANGED</remarks>
FrameChanged = 0x0020,
/// <summary>Hides the window.</summary>
/// <remarks>SWP_HIDEWINDOW</remarks>
HideWindow = 0x0080,
/// <summary>Does not activate the window. If this flag is not set, the window is activated and moved to the
/// top of either the topmost or non-topmost group (depending on the setting of the hWndInsertAfter
/// parameter).</summary>
/// <remarks>SWP_NOACTIVATE</remarks>
DoNotActivate = 0x0010,
/// <summary>Discards the entire contents of the client area. If this flag is not specified, the valid
/// contents of the client area are saved and copied back into the client area after the window is sized or
/// repositioned.</summary>
/// <remarks>SWP_NOCOPYBITS</remarks>
DoNotCopyBits = 0x0100,
/// <summary>Retains the current position (ignores X and Y parameters).</summary>
/// <remarks>SWP_NOMOVE</remarks>
IgnoreMove = 0x0002,
/// <summary>Does not change the owner window's position in the Z order.</summary>
/// <remarks>SWP_NOOWNERZORDER</remarks>
DoNotChangeOwnerZOrder = 0x0200,
/// <summary>Does not redraw changes. If this flag is set, no repainting of any kind occurs. This applies to
/// the client area, the nonclient area (including the title bar and scroll bars), and any part of the parent
/// window uncovered as a result of the window being moved. When this flag is set, the application must
/// explicitly invalidate or redraw any parts of the window and parent window that need redrawing.</summary>
/// <remarks>SWP_NOREDRAW</remarks>
DoNotRedraw = 0x0008,
/// <summary>Same as the SWP_NOOWNERZORDER flag.</summary>
/// <remarks>SWP_NOREPOSITION</remarks>
DoNotReposition = 0x0200,
/// <summary>Prevents the window from receiving the WM_WINDOWPOSCHANGING message.</summary>
/// <remarks>SWP_NOSENDCHANGING</remarks>
DoNotSendChangingEvent = 0x0400,
/// <summary>Retains the current size (ignores the cx and cy parameters).</summary>
/// <remarks>SWP_NOSIZE</remarks>
IgnoreResize = 0x0001,
/// <summary>Retains the current Z order (ignores the hWndInsertAfter parameter).</summary>
/// <remarks>SWP_NOZORDER</remarks>
IgnoreZOrder = 0x0004,
/// <summary>Displays the window.</summary>
/// <remarks>SWP_SHOWWINDOW</remarks>
ShowWindow = 0x0040,
}

Related

C# Desktop background displaying incorrect location maybe?

Hi I am currently creating an animated desktop background that uses axWindowsMideaPlayer to play video files in a loop I take the WMP and set its handle to the desktop handle, it works great on single display monitor setup but fails with multiple monitors. Why it is failing is because monitors can have their own set position like left/right/topleft/topright/top/bottom/bottomleft and bottom right of the primary screen which puts their position in the negatives and so forth.. My question is how can I position each WMP correctly on each monitor? Here is what I have so far,
this is how I get each monitor...
public class DisplayInfo
{
public bool isPrimary { get; set; }
public int ScreenHeight { get; set; }
public int ScreenWidth { get; set; }
public Rect MonitorArea { get; set; }
public Rect WorkArea { get; set; }
public string DeviceName { get; set; }
}
/// <summary>
/// Collection of display information
/// </summary>
public class DisplayInfoCollection : List<DisplayInfo>
{
// size of a device name string
private const int CCHDEVICENAME = 32;
/// <summary>
/// The MONITORINFOEX structure contains information about a display monitor.
/// The GetMonitorInfo function stores information into a MONITORINFOEX structure or a MONITORINFO structure.
/// The MONITORINFOEX structure is a superset of the MONITORINFO structure. The MONITORINFOEX structure adds a string member to contain a name
/// for the display monitor.
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal struct MONITORINFOEX
{
/// <summary>
/// The size, in bytes, of the structure. Set this member to sizeof(MONITORINFOEX) (72) before calling the GetMonitorInfo function.
/// Doing so lets the function determine the type of structure you are passing to it.
/// </summary>
public int Size;
/// <summary>
/// A RECT structure that specifies the display monitor rectangle, expressed in virtual-screen coordinates.
/// Note that if the monitor is not the primary display monitor, some of the rectangle's coordinates may be negative values.
/// </summary>
public Rect Monitor;
/// <summary>
/// A RECT structure that specifies the work area rectangle of the display monitor that can be used by applications,
/// expressed in virtual-screen coordinates. Windows uses this rectangle to maximize an application on the monitor.
/// The rest of the area in rcMonitor contains system windows such as the task bar and side bars.
/// Note that if the monitor is not the primary display monitor, some of the rectangle's coordinates may be negative values.
/// </summary>
public Rect WorkArea;
/// <summary>
/// The attributes of the display monitor.
///
/// This member can be the following value:
/// 1 : MONITORINFOF_PRIMARY
/// </summary>
public uint Flags;
/// <summary>
/// A string that specifies the device name of the monitor being used. Most applications have no use for a display monitor name,
/// and so can save some bytes by using a MONITORINFO structure.
/// </summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCHDEVICENAME)]
public string DeviceName;
public void Init()
{
this.Size = 40 + 2 * CCHDEVICENAME;
this.DeviceName = string.Empty;
}
}
[DllImport("user32.dll")]
private static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr lprcClip,
EnumMonitorsDelegate lpfnEnum, IntPtr dwData);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFOEX lpmi);
/*
[DllImport("user32.dll")]
static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFO lpmi);
*/
/// <summary>
/// Returns the number of Displays using the Win32 functions
/// </summary>
/// <returns>collection of Display Info</returns>
public static DisplayInfoCollection GetDisplays()
{
DisplayInfoCollection col = new DisplayInfoCollection();
EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero,
delegate (IntPtr hMonitor, IntPtr hdcMonitor, ref Rect lprcMonitor, IntPtr dwData)
{
MONITORINFOEX mi = new MONITORINFOEX();
mi.Size = (int)Marshal.SizeOf(mi);
bool success = GetMonitorInfo(hMonitor, ref mi);
if (success)
{
DisplayInfo di = new DisplayInfo();
di.ScreenWidth = (mi.Monitor.Right - mi.Monitor.Left);
di.ScreenHeight = (mi.Monitor.Bottom - mi.Monitor.Top);
di.MonitorArea = mi.Monitor;
di.WorkArea = mi.WorkArea;
di.isPrimary = Convert.ToBoolean(mi.Flags);
di.DeviceName = mi.DeviceName;
col.Add(di);
}
return true;
}, IntPtr.Zero);
return col;
}
}
this is how I have tried to call it and use it but it puts WMP all over the place depending on where the monitors are positioned.
DisplayInfoCollection dic = DisplayInfoCollection.GetDisplays();
int count = 0;
int totalPosX = 0;
int totalPosY = 0;
DisplayInfo dInfo = null;
List<DisplayInfo> di = dic.OrderByDescending(d => d.isPrimary).ToList();
var or = SystemInformation.VirtualScreen;
foreach (DisplayInfo dm in di)
{
bool zeroOutX = false;
bool zeroOutY = false;
if (dm.isPrimary)
{
totalPosX = or.Left > 0 ? or.Left : -or.Left;
totalPosY = or.Top > 0 ? or.Top : -or.Top;
dInfo = dm;
}
else
{
bool left = false;
bool top = false;
bool right = false;
bool bottom = false;
bool topLeft = false;
bool topRight = false;
bool bottomLeft = false;
bool bottomRight = false;
int posY = dm.MonitorArea.Top > 0 ? dm.MonitorArea.Top : -dm.MonitorArea.Top;
if (dm.MonitorArea.Left < 0)
{
left = true;
}
else
right = dm.MonitorArea.Left > 0;
if (dm.MonitorArea.Top < 0)
{
top = true;
}
else
bottom = dm.MonitorArea.Top > 0;
bool center = (dm.MonitorArea.Left > 0 ?
dm.MonitorArea.Left : -dm.MonitorArea.Left) > 0 ||
(dm.MonitorArea.Left > 0 ?
dm.MonitorArea.Left : -dm.MonitorArea.Left) < dInfo.ScreenWidth;
topLeft = left && top;
topRight = right && top;
bottomLeft = left && bottom;
bottomRight = right && bottom;
if (topLeft || topRight || bottomLeft || bottomRight || left || right)
{
if (dm.MonitorArea.Left < 0)
zeroOutX = true;
else
totalPosX += dInfo.ScreenWidth;
if (dm.MonitorArea.Top < 0)
zeroOutY = true;
else
totalPosY += dm.MonitorArea.Top;
}
dInfo = dm;
}
Display display = new Display(dm.DeviceName, dm.ScreenWidth,
dm.ScreenHeight, zeroOutX ? 0 : totalPosX,
zeroOutY ? 0 : totalPosY, Controls, count);
Displays.Add(display);
count++;
}
I cant find much help on this matter and have tried numerous ways to do this its a c# windows form and I am new-ish to programming my knowledge is limited in this any help will be appreciated thanks in advance.
According to the EnumDisplaySettings:
The EnumDisplaySettings function sets values for the following five
DEVMODE members:
dmBitsPerPel
dmPelsWidth
dmPelsHeight
dmDisplayFlags
dmDisplayFrequency
(Excluding dmPosition), You should try to use EnumDisplaySettingsEx, and specify DM_POSITION to get the correct dmPosition value.
thanks for all that helped I found a solution to my problem here it is if anyone need to know.
var or = SystemInformation.VirtualScreen;
foreach (DisplayInfo dm in dic)
{
int x = or.Left > 0 ? or.Left : -or.Left;
int y = or.Top > 0 ? or.Top : -or.Top;
if (dm.isPrimary)
{
Rect rect = new Rect();
rect.Left = x;
rect.Top = y;
rect.Right = rect.Left + dm.ScreenWidth;
rect.Bottom = rect.Top + dm.ScreenHeight;
dm.MonitorArea = rect;
}
else
{
Rect rect = new Rect();
rect.Left = x + dm.MonitorArea.Left;
rect.Top = y + dm.MonitorArea.Top;
rect.Right = rect.Left + dm.ScreenWidth;
rect.Bottom = rect.Top + dm.ScreenHeight;
dm.MonitorArea = rect;
}

Get volumes files from multi part rar file c#

I have multi-part RAR files in the same folder and I want to check if all parts of the RAR exist. I am using SharpCompress v0.24, here is my code:
using (var archive = RarArchive.Open("D:/Ontology tool.part1.rar"))
{
foreach (RarVolume vol in archive.Volumes)
{
MessageBox.Show(vol.IsMultiVolume + " \n"+ vol.IsFirstVolume+"\n"+ vol.IsSolidArchive);
}
}
But I cannot get the volume full file name.
I then use SevenZipSharp v 0.64 and 7z.dll version 19, here is my code:
using (var extractor = new SevenZipExtractor("D:/Ontology tool.part1.rar"))
{
MessageBox.Show(extractor.VolumeFileNames[0]+"");
}
But then I get the error:
Invalid archive open/read error! Is it encrypted and a wrong
password was provided? If your archive is an exotic one, it is
possible that SevenZipSharp has no signature for its format and thus
decided it is TAR by mistake
Note that the WinRAR program seems it make changes of RAR file formats because I create a RAR file with version 5.71 and when I try to open it with old WinRAR version it not opened ok, I mean files are not in the correct format.
The same applies to SevenZipSharp. If I open an old RAR file I created since 2014 it opens ok, but when I open a RAR file created with WinRAR v 5.71 it raises this error.
So now how can I get all parts files names of multi part RAR file?
Thanks for your help.
I end up using winrar.exe , send command to test file like this:
[DllImport("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl);
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private const int SW_MAXIMIZE = 3;
private const int SW_MINIMIZE = 6;
private struct WINDOWPLACEMENT
{
public int length;
public int flags;
public int showCmd;
public System.Drawing.Point ptMinPosition;
public System.Drawing.Point ptMaxPosition;
public System.Drawing.Rectangle rcNormalPosition;
}
private enum WindowShowStyle : uint
{
/// <summary>Hides the window and activates another window.</summary>
/// <remarks>See SW_HIDE</remarks>
Hide = 0,
/// <summary>Activates and displays a window. If the window is minimized
/// or maximized, the system restores it to its original size and
/// position. An application should specify this flag when displaying
/// the window for the first time.</summary>
/// <remarks>See SW_SHOWNORMAL</remarks>
ShowNormal = 1,
/// <summary>Activates the window and displays it as a minimized window.</summary>
/// <remarks>See SW_SHOWMINIMIZED</remarks>
ShowMinimized = 2,
/// <summary>Activates the window and displays it as a maximized window.</summary>
/// <remarks>See SW_SHOWMAXIMIZED</remarks>
ShowMaximized = 3,
/// <summary>Maximizes the specified window.</summary>
/// <remarks>See SW_MAXIMIZE</remarks>
Maximize = 3,
/// <summary>Displays a window in its most recent size and position.
/// This value is similar to "ShowNormal", except the window is not
/// actived.</summary>
/// <remarks>See SW_SHOWNOACTIVATE</remarks>
ShowNormalNoActivate = 4,
/// <summary>Activates the window and displays it in its current size
/// and position.</summary>
/// <remarks>See SW_SHOW</remarks>
Show = 5,
/// <summary>Minimizes the specified window and activates the next
/// top-level window in the Z order.</summary>
/// <remarks>See SW_MINIMIZE</remarks>
Minimize = 6,
/// <summary>Displays the window as a minimized window. This value is
/// similar to "ShowMinimized", except the window is not activated.</summary>
/// <remarks>See SW_SHOWMINNOACTIVE</remarks>
ShowMinNoActivate = 7,
/// <summary>Displays the window in its current size and position. This
/// value is similar to "Show", except the window is not activated.</summary>
/// <remarks>See SW_SHOWNA</remarks>
ShowNoActivate = 8,
/// <summary>Activates and displays the window. If the window is
/// minimized or maximized, the system restores it to its original size
/// and position. An application should specify this flag when restoring
/// a minimized window.</summary>
/// <remarks>See SW_RESTORE</remarks>
Restore = 9,
/// <summary>Sets the show state based on the SW_ value specified in the
/// STARTUPINFO structure passed to the CreateProcess function by the
/// program that started the application.</summary>
/// <remarks>See SW_SHOWDEFAULT</remarks>
ShowDefault = 10,
/// <summary>Windows 2000/XP: Minimizes a window, even if the thread
/// that owns the window is hung. This flag should only be used when
/// minimizing windows from a different thread.</summary>
/// <remarks>See SW_FORCEMINIMIZE</remarks>
ForceMinimized = 11
}
[DllImport("user32.dll")]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
public static extern IntPtr GetParent(IntPtr hWnd);
const int SW_RESTORE = 9;
[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")]
static extern bool MoveWindow(IntPtr Handle, int x, int y, int w, int h, bool repaint);
static readonly int GWL_STYLE = -16;
static readonly int WS_VISIBLE = 0x10000000;
....
private string GetMissingCompressedFile(string FilePath, string WinRARPath)
{
string MissingCompressedFile = "";
Process p = new Process();
p.StartInfo.FileName = WinRARPath;
p.EnableRaisingEvents = true;
// -ibck -inul
p.StartInfo.Arguments = " t " + " \"" + FilePath + "\"";
//p.StartInfo.UseShellExecute = false;
// p.StartInfo.RedirectStandardOutput = true;
//p.StartInfo.RedirectStandardError = true;
//p.StartInfo.CreateNoWindow = true;
p.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
IntPtr PanelHandler=new IntPtr();
WinRARPanel_Ref.Invoke((MethodInvoker)delegate
{
PanelHandler = WinRARPanel_Ref.Handle;
});
p.Start();
IntPtr h = p.MainWindowHandle;
while (true)
{
if (p.HasExited)
break;
if (p.MainWindowHandle != IntPtr.Zero)
break;
Thread.Sleep(100); // Don't hog the CPU
p.Refresh(); // You need this since `MainWindowHandle` is cached
}
if (!p.HasExited)
{
SetParent(p.MainWindowHandle, PanelHandler);
//SetWindowLong(p.MainWindowHandle, GWL_STYLE, WS_VISIBLE);
//MoveWindow(p.MainWindowHandle, 0, 0, WinRARPanel_Ref.Width, WinRARPanel_Ref.Height, true);
}
while (!p.HasExited)
{
var _windowHandle = FindWindow(null, "Next volume is required");
var _parent = GetParent(_windowHandle);
if (_parent == p.MainWindowHandle)
{
if (!p.HasExited)
{
SetParent(_windowHandle, WinRARPanel_Ref.Handle);
}
Thread.Sleep(1000);
if (!p.HasExited)
{
MainForm_Ref.Invoke((MethodInvoker)delegate
{
Clipboard.Clear();
ShowWindow(h, SW_RESTORE);
SetForegroundWindow(h);
SendKeys.SendWait("^(c)");
string ClipboardText = Clipboard.GetText();
if (!string.IsNullOrEmpty(ClipboardText))
{
try
{
string n = new FileInfo(ClipboardText).Name;
MissingCompressedFile = ClipboardText;
if (!p.HasExited)
{
p.Kill();
}
}
catch
{
if (ClipboardText.Contains("You need to start extraction from a previous volume to unpack"))
{
MissingCompressedFile = "";
p.Kill();
}
}
Clipboard.Clear();
}
});
}
}
else
{
if (!p.HasExited)
{
MainForm_Ref.Invoke((MethodInvoker)delegate
{
Clipboard.Clear();
if (!p.HasExited)
{
ShowWindow(h, SW_RESTORE);
SetForegroundWindow(h);
}
SendKeys.SendWait("^(c)");
string ClipboardText = Clipboard.GetText();
if (!string.IsNullOrEmpty(ClipboardText))
{
try
{
string n = new FileInfo(ClipboardText).Name;
MissingCompressedFile = ClipboardText;
if (!p.HasExited)
{
p.Kill();
}
}
catch
{
if (ClipboardText.Contains("You need to start extraction from a previous volume to unpack"))
{
MissingCompressedFile = "";
p.Kill();
}
}
Clipboard.Clear();
}
});
}
}
}
if (!p.HasExited)
{
p.Kill();
}
p = null;
return MissingCompressedFile;
}

How prevent the form hide after the dialog close (C# Windows Mobile)

I'm doing a mobile application, all is almost as WindowsForms but when I close a MessageBox that provoque the multiple dialogs close with DialogResult in DialogResult.OK I find a problem, the main form it hides.
The structure is as follows:
program.cs
Application.Run(new From1());
Form1
Dialog1 frmDialog1 = new Dialog1());
frmDialog1.ShowDialog(this);
Dialog1(Windows Parent)
Dialog2 frmDialog2 = new Dialog2());
frmDialog2.ShowDialog(this);
if(frmDialog2.DialogResult == DialogResult.OK)
{
this.DialogResult = DialogResult.OK;
this.Close();
}
Dialog2(Windows Parent)
Dialog3 frmDialog3 = new Dialog3());
frmDialog3.ShowDialog(this);
if(frmDialog3.DialogResult == DialogResult.OK)
{
this.DialogResult = DialogResult.OK;
this.ParentForm.Hide();
this.Close();
}
Dialog3(Windows Parent)
if (MessageBox.Show("Do you want to save?", "Save?",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button1) == DialogResult.Yes)
{
this.DialogResult = DialogResult.OK;
this.ParentForm.Hide();
this.Close();
}
**Note: I'm using [DllImport("coredll.dll")] to show full screen
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
[Flags()]
public enum FullScreenFlags : int
{
SwHide = 0,
ShowTaskbar = 0x1,
HideTaskbar = 0x2,
ShowSipButton = 0x4,
HideSipButton = 0x8,
SwRestore = 9,
ShowStartIcon = 0x10,
HideStartIcon = 0x20
}
static class FullScreen
{
#region Win32 API Calls
/// <summary>
/// The GetCapture function retrieves a handle to the window
/// </summary>
/// <returns></returns>
[DllImport("coredll.dll")]
private static extern IntPtr GetCapture();
/// <summary>
/// The SetCapture function sets the mouse capture to
/// the specified window belonging to the current thread
/// </summary>
/// <param name="hWnd"></param>
/// <returns></returns>
[DllImport("coredll.dll")]
private static extern IntPtr SetCapture(IntPtr hWnd);
/// <summary>
/// This function can be used to take over certain areas of the screen
/// It is used to modify the taskbar, Input Panel button,
/// or Start menu icon.
/// </summary>
/// <param name="hwnd"></param>
/// <param name="state"></param>
/// <returns></returns>
[DllImport("aygshell.dll", SetLastError = true)]
private static extern bool SHFullScreen(IntPtr hwnd, int state);
/// <summary>
/// The function retrieves the handle to the top-level
/// window whose class name and window name match
/// the specified strings. This function does not search child windows.
/// </summary>
/// <param name="lpClass"></param>
/// <param name="lpWindow"></param>
/// <returns></returns>
[DllImport("coredll.dll", SetLastError = true)]
private static extern IntPtr FindWindowW(string lpClass, string
lpWindow);
/// <summary>
/// changes the position and dimensions of the specified window
/// </summary>
/// <param name="hwnd"></param>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="w"></param>
/// <param name="l"></param>
/// <param name="repaint"></param>
/// <returns></returns>
[DllImport("coredll.dll", SetLastError = true)]
private static extern IntPtr MoveWindow(IntPtr hwnd, int x, int y, int
w, int l, int repaint);
#endregion
#region General Methods
/// <summary>
/// obtain the window handle of a .Net window or control
/// </summary>
/// <param name="c"></param>
/// <returns></returns>
public static IntPtr GetHWnd(Control c)
{
IntPtr hOldWnd = GetCapture();
c.Capture = true;
IntPtr hWnd = GetCapture();
c.Capture = false;
SetCapture(hOldWnd);
return hWnd;
}
/// <summary>
/// Set Full Screen Mode
/// </summary>
/// <param name="form"></param>
public static void StartFullScreen(Form form)
{
//if not Pocket Pc platform
if (!Platform.PlatformDetection.IsPocketPC())
{
//Set Full Screen For Windows CE Device
//Normalize windows state
form.WindowState = FormWindowState.Normal;
IntPtr iptr = form.Handle;
SHFullScreen(iptr, (int)FullScreenFlags.HideStartIcon);
//detect taskbar height
int taskbarHeight = Screen.PrimaryScreen.Bounds.Height - Screen.PrimaryScreen.WorkingArea.Height;
// move the viewing window north taskbar height to get rid of the command
//bar
MoveWindow(iptr, 0, -taskbarHeight, Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height + taskbarHeight, 1);
// move the task bar south taskbar height so that its not visible anylonger
IntPtr iptrTB = FindWindowW("HHTaskBar", null);
MoveWindow(iptrTB, 0, Screen.PrimaryScreen.Bounds.Height, Screen.PrimaryScreen.Bounds.Width, taskbarHeight, 1);
}
else //pocket pc platform
{
//Set Full Screen For Pocket Pc Device
form.Menu = null;
form.ControlBox = false;
form.FormBorderStyle = FormBorderStyle.None;
form.WindowState = FormWindowState.Maximized;
form.Text = string.Empty;
}
}
/// <summary>
/// Stop Full Screen Mode
/// </summary>
/// <param name="form"></param>
public static void StopFullScreen(Form form)
{
//if windows ce return window and taskbar to his original place
if (!Platform.PlatformDetection.IsPocketPC())
{
IntPtr iptr = form.Handle;
SHFullScreen(iptr, (int)FullScreenFlags.ShowStartIcon);
//detect taskbar height
int taskbarHeight = Screen.PrimaryScreen.Bounds.Height - Screen.PrimaryScreen.WorkingArea.Height;
MoveWindow(iptr, 0, 0, Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height - taskbarHeight, 1);
IntPtr iptrTB = FindWindowW("HHTaskBar", null);
MoveWindow(iptrTB, 0, Screen.PrimaryScreen.Bounds.Height - taskbarHeight, Screen.PrimaryScreen.Bounds.Width, taskbarHeight, 1);
}
}
#endregion
}
**Other comment:
I´m calling this.ParentFormHide(); because I desire that the parent it is hide before then close it. This for prevent then it show wrong, as like the follows:
This is shown when is closing multiple dialogs in cascade
If you know a way to prevent this animation on closing multiple dialogs, please share to me. At present to prevent this, I'm hiding the previous dialog before to close it.
Thanks in advance

How to send touch event in Geckofx?

I use Geckofx in my program.I just want to send touch event (like touchstart , touchmove , touchend) to the document of Geckobrowser.I had try to add the method in "WindowUtils.cs" of "Gecko-core.dll" ,like that:
public Boolean SendTouchEvent(string aType, uint[] aIdentifiers, int[] aXs, int[] aYs, uint[] aRxs, uint[] aRys, float[] aRotationAngles, float[] aForces, uint count, int aModifiers, bool aIgnoreRootScrollFrame)
{
using (nsAString type = new nsAString(aType))
{
return _windowUtils.Instance.SendTouchEvent(type, aIdentifiers, aXs, aYs, aRxs, aRys, aRotationAngles, aForces, count, aModifiers, aIgnoreRootScrollFrame);
}
}
This method uses the the method "SendTouchEvent" in "nsIDOMWindowUtils.cs", like that :
/// <summary>
///Synthesize a touch event. The event types supported are:
/// touchstart, touchend, touchmove, and touchcancel
///
/// Events are sent in coordinates offset by aX and aY from the window.
///
/// Cannot be accessed from unprivileged context (not content-accessible)
/// Will throw a DOM security error if called without chrome privileges.
///
/// The event is dispatched via the toplevel window, so it could go to any
/// window under the toplevel window, in some cases it could never reach this
/// window at all.
///
/// #param aType event type
/// #param xs array of offsets in CSS pixels for each touch to be sent
/// #param ys array of offsets in CSS pixels for each touch to be sent
/// #param rxs array of radii in CSS pixels for each touch to be sent
/// #param rys array of radii in CSS pixels for each touch to be sent
/// #param rotationAngles array of angles in degrees for each touch to be sent
/// #param forces array of forces (floats from 0 to 1) for each touch to be sent
/// #param count number of touches in this set
/// #param aModifiers modifiers pressed, using constants defined as MODIFIER_*
/// #param aIgnoreRootScrollFrame whether the event should ignore viewport bounds
/// during dispatch
///
/// returns true if the page called prevent default on this touch event
/// </summary>
[return: MarshalAs(UnmanagedType.U1)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
bool SendTouchEvent([MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = "Gecko.CustomMarshalers.AStringMarshaler")] nsAStringBase aType, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=8)] uint[] aIdentifiers, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=8)] int[] aXs, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=8)] int[] aYs, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=8)] uint[] aRxs, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=8)] uint[] aRys, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=8)] float[] aRotationAngles, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=8)] float[] aForces, uint count, int aModifiers, [MarshalAs(UnmanagedType.U1)] bool aIgnoreRootScrollFrame);
And then , I test my method like that :
private void button2_Click(object sender, EventArgs e)
{
uint[] ident ={1};
int[] ax={200};
int[] ay={200};
uint[] rx ={2};
uint[] ry ={2};
float[] ro ={20};
float[] force={(float)0.8};
bool r = browser.Window.WindowUtils.SendTouchEvent("touchstart", ident, ax, ay, rx, ry, ro, force, (uint)1, 0, true);
Application.DoEvents();
for (int i = 0; i < 100; i++)
{
ay[0]+=10;
r = browser.Window.WindowUtils.SendTouchEvent("touchmove", ident, ax, ay, rx, ry, ro, force, (uint)1, 0, true);
Application.DoEvents();
Thread.Sleep(10);
}
r = browser.Window.WindowUtils.SendTouchEvent("touchend", ident, ax, ay, rx, ry, ro, force, (uint)1, 0, true);
}
But, it always returns false;Could Anyone help me? Thanks in advance.

How to get a form's maximized client size without maximizing it?

How to get the client size of a Form when it's maximized without maximize it?
From example, I want to create a Bitmap with the same size of the maximized Form's client size, how can I do that?
Try
Screen.FromControl(this).GetWorkingArea();
to calculate the size (without taskbar)
then substract the difference between the Forms ClientSize / Size.
Hope that works, haven't tested it.
Update:
A bit hacky, but I tried it and it works.
var frm = new Form();
frm.Opacity = 100;
frm.WindowState = FormWindowState.Maximized;
frm.Show();
while (!frm.IsHandleCreated)
System.Threading.Thread.Sleep(1);
var result = frm.ClientSize;
frm.Close();
return result;
Update2:
This is a nicer solution.
I disable painting of the Form, maximize it, get the client area, set it back to normal and return the result. Works well, without flicker or something.
private static Size GetMaximizedClientSize(Form form)
{
var original = form.WindowState;
try
{
BeginUpdate(form);
form.WindowState = FormWindowState.Maximized;
return form.ClientSize;
}
finally
{
form.WindowState = original;
EndUpdate(form);
}
}
[DllImport("User32.dll")]
private extern static int SendMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
private enum Message : int
{
WM_SETREDRAW = 0x000B, // int 11
}
/// <summary>
/// Calls user32.dll SendMessage(handle, WM_SETREDRAW, 0, null) native function to disable painting
/// </summary>
/// <param name="c"></param>
public static void BeginUpdate(Control c)
{
SendMessage(c.Handle, (int)Message.WM_SETREDRAW, new IntPtr(0), IntPtr.Zero);
}
/// <summary>
/// Calls user32.dll SendMessage(handle, WM_SETREDRAW, 1, null) native function to enable painting
/// </summary>
/// <param name="c"></param>
public static void EndUpdate(Control c)
{
SendMessage(c.Handle, (int)Message.WM_SETREDRAW, new IntPtr(1), IntPtr.Zero);
}
Try the following link,
http://msdn.microsoft.com/en-us/library/system.windows.forms.screen.workingarea%28VS.71%29.aspx

Categories

Resources