From 8fc8b1fa271c7e8d577b9e40b5c48c5a83564385 Mon Sep 17 00:00:00 2001 From: "Vyacheslav N. Boyko" Date: Thu, 5 Jul 2018 14:30:05 +0300 Subject: [PATCH] set window position --- .gitignore | 3 + Form1.Designer.cs | 179 +++++++++++++++++++++++++++++++ Form1.cs | 146 +++++++++++++++++++++++++ Form1.resx | 120 +++++++++++++++++++++ Program.cs | 21 ++++ Properties/AssemblyInfo.cs | 36 +++++++ Properties/Resources.Designer.cs | 63 +++++++++++ Properties/Resources.resx | 117 ++++++++++++++++++++ Properties/Settings.Designer.cs | 26 +++++ Properties/Settings.settings | 7 ++ SetWindowPosition.csproj | 118 ++++++++++++++++++++ SetWindowPosition.csproj.user | 12 +++ SetWindowPosition.sln | 25 +++++ WindowInfo.cs | 21 ++++ 14 files changed, 894 insertions(+) create mode 100644 .gitignore create mode 100644 Form1.Designer.cs create mode 100644 Form1.cs create mode 100644 Form1.resx create mode 100644 Program.cs create mode 100644 Properties/AssemblyInfo.cs create mode 100644 Properties/Resources.Designer.cs create mode 100644 Properties/Resources.resx create mode 100644 Properties/Settings.Designer.cs create mode 100644 Properties/Settings.settings create mode 100644 SetWindowPosition.csproj create mode 100644 SetWindowPosition.csproj.user create mode 100644 SetWindowPosition.sln create mode 100644 WindowInfo.cs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..03c9b93 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +bin/ +obj/ +.vs/ diff --git a/Form1.Designer.cs b/Form1.Designer.cs new file mode 100644 index 0000000..6532594 --- /dev/null +++ b/Form1.Designer.cs @@ -0,0 +1,179 @@ +namespace SetWindowPosition +{ + partial class Form1 + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.btnSet = new System.Windows.Forms.Button(); + this.txtY = new System.Windows.Forms.TextBox(); + this.label4 = new System.Windows.Forms.Label(); + this.txtX = new System.Windows.Forms.TextBox(); + this.label5 = new System.Windows.Forms.Label(); + this.txtHeight = new System.Windows.Forms.TextBox(); + this.label3 = new System.Windows.Forms.Label(); + this.txtWidth = new System.Windows.Forms.TextBox(); + this.label2 = new System.Windows.Forms.Label(); + this.label1 = new System.Windows.Forms.Label(); + this.comboBox1 = new System.Windows.Forms.ComboBox(); + this.SuspendLayout(); + // + // btnSet + // + this.btnSet.Location = new System.Drawing.Point(15, 141); + this.btnSet.Name = "btnSet"; + this.btnSet.Size = new System.Drawing.Size(126, 23); + this.btnSet.TabIndex = 21; + this.btnSet.Text = "Set"; + this.btnSet.UseVisualStyleBackColor = true; + this.btnSet.Click += new System.EventHandler(this.btnSet_Click); + // + // txtY + // + this.txtY.Location = new System.Drawing.Point(70, 115); + this.txtY.Name = "txtY"; + this.txtY.Size = new System.Drawing.Size(71, 20); + this.txtY.TabIndex = 20; + this.txtY.Text = "10"; + // + // label4 + // + this.label4.AutoSize = true; + this.label4.Location = new System.Drawing.Point(12, 118); + this.label4.Name = "label4"; + this.label4.Size = new System.Drawing.Size(17, 13); + this.label4.TabIndex = 19; + this.label4.Text = "Y:"; + // + // txtX + // + this.txtX.Location = new System.Drawing.Point(70, 89); + this.txtX.Name = "txtX"; + this.txtX.Size = new System.Drawing.Size(71, 20); + this.txtX.TabIndex = 18; + this.txtX.Text = "10"; + // + // label5 + // + this.label5.AutoSize = true; + this.label5.Location = new System.Drawing.Point(12, 92); + this.label5.Name = "label5"; + this.label5.Size = new System.Drawing.Size(17, 13); + this.label5.TabIndex = 17; + this.label5.Text = "X:"; + // + // txtHeight + // + this.txtHeight.Location = new System.Drawing.Point(70, 63); + this.txtHeight.Name = "txtHeight"; + this.txtHeight.Size = new System.Drawing.Size(71, 20); + this.txtHeight.TabIndex = 16; + this.txtHeight.Text = "150"; + // + // label3 + // + this.label3.AutoSize = true; + this.label3.Location = new System.Drawing.Point(12, 66); + this.label3.Name = "label3"; + this.label3.Size = new System.Drawing.Size(41, 13); + this.label3.TabIndex = 15; + this.label3.Text = "Height:"; + // + // txtWidth + // + this.txtWidth.Location = new System.Drawing.Point(70, 37); + this.txtWidth.Name = "txtWidth"; + this.txtWidth.Size = new System.Drawing.Size(71, 20); + this.txtWidth.TabIndex = 14; + this.txtWidth.Text = "300"; + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(12, 40); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(38, 13); + this.label2.TabIndex = 13; + this.label2.Text = "Width:"; + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(12, 14); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(52, 13); + this.label1.TabIndex = 11; + this.label1.Text = "App Title:"; + // + // comboBox1 + // + this.comboBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.comboBox1.FormattingEnabled = true; + this.comboBox1.Location = new System.Drawing.Point(71, 13); + this.comboBox1.Name = "comboBox1"; + this.comboBox1.Size = new System.Drawing.Size(251, 21); + this.comboBox1.TabIndex = 22; + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(334, 173); + this.Controls.Add(this.comboBox1); + this.Controls.Add(this.btnSet); + this.Controls.Add(this.txtY); + this.Controls.Add(this.label4); + this.Controls.Add(this.txtX); + this.Controls.Add(this.label5); + this.Controls.Add(this.txtHeight); + this.Controls.Add(this.label3); + this.Controls.Add(this.txtWidth); + this.Controls.Add(this.label2); + this.Controls.Add(this.label1); + this.Name = "Form1"; + this.Text = "Set window position"; + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Button btnSet; + private System.Windows.Forms.TextBox txtY; + private System.Windows.Forms.Label label4; + private System.Windows.Forms.TextBox txtX; + private System.Windows.Forms.Label label5; + private System.Windows.Forms.TextBox txtHeight; + private System.Windows.Forms.Label label3; + private System.Windows.Forms.TextBox txtWidth; + private System.Windows.Forms.Label label2; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.ComboBox comboBox1; + } +} + diff --git a/Form1.cs b/Form1.cs new file mode 100644 index 0000000..bfb4870 --- /dev/null +++ b/Form1.cs @@ -0,0 +1,146 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Windows.Forms; + +using System.Runtime.InteropServices; + +using HWND = System.IntPtr; + +namespace SetWindowPosition +{ + public partial class Form1 : Form + { + public Form1() + { + InitializeComponent(); + preloadProcesses(); + } + + // Define the FindWindow API function. + [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)] + static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName); + + // Define the SetWindowPos API function. + [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); + + [DllImport("USER32.DLL")] + private static extern IntPtr GetShellWindow(); + + private delegate bool EnumWindowsProc(HWND hWnd, int lParam); + + [DllImport("USER32.DLL")] + private static extern bool EnumWindows(EnumWindowsProc enumFunc, int lParam); + + [DllImport("USER32.DLL")] + private static extern bool IsWindowVisible(HWND hWnd); + + [DllImport("USER32.DLL")] + private static extern int GetWindowTextLength(HWND hWnd); + + [DllImport("USER32.DLL")] + private static extern int GetWindowText(HWND hWnd, StringBuilder lpString, int nMaxCount); + + [DllImport("user32")] + private static extern UInt32 GetWindowThreadProcessId(Int32 hWnd, out Int32 lpdwProcessId); + + public static Int32 GetWindowProcessID(Int32 hwnd) { + Int32 pid = 1; + GetWindowThreadProcessId(hwnd, out pid); + return pid; + } + + // Define the SetWindowPosFlags enumeration. + [Flags()] + private enum SetWindowPosFlags : uint + { + SynchronousWindowPosition = 0x4000, + DeferErase = 0x2000, + DrawFrame = 0x0020, + FrameChanged = 0x0020, + HideWindow = 0x0080, + DoNotActivate = 0x0010, + DoNotCopyBits = 0x0100, + IgnoreMove = 0x0002, + DoNotChangeOwnerZOrder = 0x0200, + DoNotRedraw = 0x0008, + DoNotReposition = 0x0200, + DoNotSendChangingEvent = 0x0400, + IgnoreResize = 0x0001, + IgnoreZOrder = 0x0004, + ShowWindow = 0x0040, + } + + /// Returns a dictionary that contains the handle and title of all the open windows. + /// A dictionary that contains the handle and title of all the open windows. + public static HashSet GetOpenWindows() { + HWND shellWindow = GetShellWindow(); + + HashSet windows = new HashSet(); + + EnumWindows(delegate (HWND hWnd, int lParam) + { + if (hWnd == shellWindow) return true; + if (!IsWindowVisible(hWnd)) return true; + + int length = GetWindowTextLength(hWnd); + if (length == 0) return true; + + StringBuilder builder = new StringBuilder(length); + GetWindowText(hWnd, builder, length + 1); + + Int32 pid = GetWindowProcessID(hWnd.ToInt32()); + Process p = Process.GetProcessById(pid); + string appName = p.ProcessName; + + WindowInfo window = new WindowInfo(hWnd, appName, builder.ToString()); + + windows.Add(window); + return true; + + }, 0); + + return windows; + } + + private void preloadProcesses() { + HashSet allWindows = GetOpenWindows(); + foreach (WindowInfo windowData in allWindows) { + comboBox1.Items.Add(windowData); + } + } + + // Size and position the application. + private void btnSet_Click(object sender, EventArgs e) + { + + // Get the target window's handle. + IntPtr target_hwnd = //FindWindowByCaption(IntPtr.Zero, txtAppTitle.Text); + ((WindowInfo) comboBox1.SelectedItem).hWnd; + if (target_hwnd == IntPtr.Zero) + { + MessageBox.Show( + "Could not find a window with the title \"" + + ((WindowInfo) comboBox1.SelectedItem).title+ "\""); + return; + } + + + // Set the window's position. + int width = int.Parse(txtWidth.Text); + int height = int.Parse(txtHeight.Text); + int x = int.Parse(txtX.Text); + int y = int.Parse(txtY.Text); + SetWindowPos(target_hwnd, IntPtr.Zero, x, y, width, height, 0); + } + + + } +} diff --git a/Form1.resx b/Form1.resx new file mode 100644 index 0000000..19dc0dd --- /dev/null +++ b/Form1.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Program.cs b/Program.cs new file mode 100644 index 0000000..34de308 --- /dev/null +++ b/Program.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Windows.Forms; + +namespace SetWindowPosition +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + } +} diff --git a/Properties/AssemblyInfo.cs b/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..3634127 --- /dev/null +++ b/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("SetWindowPosition")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("bvn13")] +[assembly: AssemblyProduct("SetWindowPosition")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("4aa11c22-a4cf-4bcb-84ab-ac13708d72de")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Properties/Resources.Designer.cs b/Properties/Resources.Designer.cs new file mode 100644 index 0000000..93db4af --- /dev/null +++ b/Properties/Resources.Designer.cs @@ -0,0 +1,63 @@ +//------------------------------------------------------------------------------ +// +// Этот код создан программой. +// Исполняемая версия:4.0.30319.42000 +// +// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае +// повторной генерации кода. +// +//------------------------------------------------------------------------------ + +namespace SetWindowPosition.Properties { + using System; + + + /// + /// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д. + /// + // Этот класс создан автоматически классом StronglyTypedResourceBuilder + // с помощью такого средства, как ResGen или Visual Studio. + // Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen + // с параметром /str или перестройте свой проект VS. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SetWindowPosition.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Перезаписывает свойство CurrentUICulture текущего потока для всех + /// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + } +} diff --git a/Properties/Resources.resx b/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Properties/Settings.Designer.cs b/Properties/Settings.Designer.cs new file mode 100644 index 0000000..95f24f1 --- /dev/null +++ b/Properties/Settings.Designer.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// Этот код создан программой. +// Исполняемая версия:4.0.30319.42000 +// +// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае +// повторной генерации кода. +// +//------------------------------------------------------------------------------ + +namespace SetWindowPosition.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.7.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default { + get { + return defaultInstance; + } + } + } +} diff --git a/Properties/Settings.settings b/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/SetWindowPosition.csproj b/SetWindowPosition.csproj new file mode 100644 index 0000000..7680e18 --- /dev/null +++ b/SetWindowPosition.csproj @@ -0,0 +1,118 @@ + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {A2432D67-CB1A-4E63-B46C-9B46688449E2} + WinExe + Properties + SetWindowPosition + SetWindowPosition + v3.5 + 512 + + + + + 3.5 + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + 3.5 + + + 3.5 + + + 3.5 + + + + + + + + + + + Form + + + Form1.cs + + + + + Form1.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + True + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + False + .NET Framework 3.5 SP1 + true + + + + + \ No newline at end of file diff --git a/SetWindowPosition.csproj.user b/SetWindowPosition.csproj.user new file mode 100644 index 0000000..3e8fd5e --- /dev/null +++ b/SetWindowPosition.csproj.user @@ -0,0 +1,12 @@ + + + + + + + + + ru-RU + false + + \ No newline at end of file diff --git a/SetWindowPosition.sln b/SetWindowPosition.sln new file mode 100644 index 0000000..e5a1fb3 --- /dev/null +++ b/SetWindowPosition.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27703.2035 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SetWindowPosition", "SetWindowPosition.csproj", "{A2432D67-CB1A-4E63-B46C-9B46688449E2}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A2432D67-CB1A-4E63-B46C-9B46688449E2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A2432D67-CB1A-4E63-B46C-9B46688449E2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A2432D67-CB1A-4E63-B46C-9B46688449E2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A2432D67-CB1A-4E63-B46C-9B46688449E2}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {2983813D-F1E0-49DA-80AC-633AEDC09A99} + EndGlobalSection +EndGlobal diff --git a/WindowInfo.cs b/WindowInfo.cs new file mode 100644 index 0000000..8f288d3 --- /dev/null +++ b/WindowInfo.cs @@ -0,0 +1,21 @@ +using System; + +using HWND = System.IntPtr; + +namespace SetWindowPosition { + public class WindowInfo { + public HWND hWnd; + public string name; + public string title; + + public WindowInfo(HWND hWnd, string name, string title) { + this.hWnd = hWnd; + this.name = name; + this.title = title; + } + + public override string ToString() { + return "" + hWnd.ToString() + " | " + name + " | " + title.ToString(); + } + } +}