How to get position of c# console application - c#

I am a beginner at coding and I want to create an application that says the width, height, and position of the window.
The problem is that I don't know how to GET the position of the window.
I searched the internet but couldn't find the answer to my question.
Here is the code I have:
using System;
namespace WindowSizeChecker
{
class Program
{
const bool alwaysTrue = true;
static void Main(string[] args)
{
while (alwaysTrue == true)
{
Console.Write("Set your console window to your prefered size and position. Then press Enter");
Console.ReadLine();
screenSizeAndPosition();
Console.WriteLine("\n\nPress enter to repeat\n\n");
Console.ReadLine();
}
}
public static void screenSizeAndPosition()
{
int consoleWidth = Console.WindowWidth;
int consoleHeight = Console.WindowHeight;
string consoleWidthString = consoleWidth.ToString();
string consoleHeightString = consoleHeight.ToString();
Console.WriteLine("\nThe width of the window is: {0}\nAnd the height of the window is: {1}", consoleWidthString, consoleHeightString);
int largestWindowWidth = Console.LargestWindowWidth;
int largestWindowHeight = Console.LargestWindowHeight;
string largestWindowWidthString = largestWindowWidth.ToString();
string largestWindowHeightString = largestWindowHeight.ToString();
Console.WriteLine("\nThe largest width of the window is: {0}\nAnd the largest height of the window is: {1}", largestWindowWidthString, largestWindowHeightString);
}
}
}
Here is the program running:
enter image description here

I am a beginner at coding and I want to create an application that says the width, height, and position of the window. The problem is that I don't know how to GET the position of the window. I searched the internet but couldn't find the answer to my question.
The information is out there, but I admit, it's not necessarily presented in the easiest to understand manner, especially for a beginner.
IMHO, two of the most relevant Stack Overflow questions you probably should read are these:
Position a small console window to the bottom left of the screen?
DwmGetWindowAttribute returns 0 with PInvoke
They aren't really duplicates of your question, and for a beginner it's probably hard to see how they answer it. But they do in fact contain almost all of the information you would need.
There are a couple of things you need to understand, besides the "how":
The Console properties you're looking at now are not pixel dimensions, but rather are in terms of character columns and rows. That is, how many characters can fit across the window in a single row, and how many rows of those characters can fit vertically.
When it comes to pixels, there are actually (at least) two different ways to look at the window size: raw screen coordinates, and "DPI-adjusted". The latter is IMHO a misnomer, because it's not taking into account any actual screen resolution (i.e. "dots per inch"), but rather the scaling factor that is set for your desktop. It's considered "DPI-adjusted" because setting the scaling factor is the Windows mechanism for attempting to keep the visual presentation of a program consistent across displays of different resolution.
As you already have seen, you can get the character-oriented dimensions straight from the .NET Console class. But to get the pixel information, you need to use .NET's native interop support to call the Windows API directly. Here are some helper classes I put together, based on available documentation and Stack Overflow posts, to do that for your scenario:
[StructLayout(LayoutKind.Sequential)]
struct Rect
{
public int Left;
public int Top;
public int Right;
public int Bottom;
public int Width => Right - Left;
public int Height => Bottom - Top;
}
class NativeConsole
{
[DllImport("kernel32")]
public static extern IntPtr GetConsoleWindow();
}
class Winuser
{
[DllImport(#"user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetWindowRect(IntPtr hWnd, out Rect lpRect);
public static Rect GetWindowRect(IntPtr handle)
{
if (!GetWindowRect(handle, out Rect rect))
{
throw Marshal.GetExceptionForHR(Marshal.GetLastWin32Error());
}
return rect;
}
}
class DwmApi
{
private const int DWMWA_EXTENDED_FRAME_BOUNDS = 9;
[DllImport(#"dwmapi.dll")]
private static extern int DwmGetWindowAttribute(IntPtr hwnd, int dwAttribute, out Rect pvAttribute, int cbAttribute);
public static Rect GetExtendedFrameBounds(IntPtr hwnd)
{
int hresult = DwmGetWindowAttribute(hwnd, DWMWA_EXTENDED_FRAME_BOUNDS, out Rect rect, Marshal.SizeOf(typeof(Rect)));
if (hresult != 0)
{
throw Marshal.GetExceptionForHR(hresult);
}
return rect;
}
}
You could, of course, lump all of the above together in a single class, but I prefer to keep things organized. The above groups the various parts of the API into the same organization used in the native Win32 API itself.
With those pieces in hand, now we can put together a program similar to the one you have above, except that it will display the window position (which is what you want), along with the width and height as well (since those come for free from the native API anyway).
That looks like this:
using static System.Console;
class Program
{
static void Main(string[] args)
{
Clear();
string prompt = "Set your console window to your preferred size and position. Press X to exit";
while (true)
{
if (KeyAvailable && ReadKey(intercept: true).Key == ConsoleKey.X)
{
break;
}
ScreenSizeAndPosition(prompt);
System.Threading.Thread.Sleep(TimeSpan.FromSeconds(0.25));
}
}
static void ScreenSizeAndPosition(string prompt)
{
string format = $"{{0, {-WindowWidth}}}";
SetCursorPosition(0, 0);
Write(format, prompt);
Write(format, $"Window is {WindowWidth} columns wide and {WindowHeight} rows high");
Write(format, $"The largest window that can fit on the screen is {LargestWindowWidth} columns wide and {LargestWindowHeight} rows high");
IntPtr consoleHwnd = NativeConsole.GetConsoleWindow();
Rect winuserRect = Winuser.GetWindowRect(consoleHwnd),
dwmRect = DwmApi.GetExtendedFrameBounds(consoleHwnd);
Write(format, $"DPI-adjusted screen values: location is {{{winuserRect.Left}, {winuserRect.Top}}}, window is {winuserRect.Width} pixels wide, {winuserRect.Height} pixels high");
Write(format, $"Desktop Window Manager values: location is {{{dwmRect.Left}, {dwmRect.Top}}}, window is {dwmRect.Width} pixels wide, {dwmRect.Height} pixels high");
for (int i = 0; i < WindowHeight - 5; i++)
{
Write(format, "");
}
}
}
I did change your basic logic in the program a bit, so that it just checks every quarter second rather than waiting for the user to press a key, displaying whatever the current values are as the user changes the window size and position.
For more details on the Windows functions used above, you should read the documentation:
GetConsoleWindow()
GetWindowRect()
DwmGetWindowAttribute()
There are some additional subtleties in the ways that GetWindowRect() and DwmGetWindowAttribute() work, so it's worth checking out the docs so that you understand better what they are returning in terms of the window dimensional values.

You should call a Win32 API DwmGetWindowAttribute via PInovke to the current window position. Refer to the document and see how to use it.

Related

C# Screen size without references in interactive

I want to get the screen size of the primary screen, without adding any references (e.g. WinForms or Presentation). I found a similar question here, however there is no solution which doesn't include downloading or something like that.
But I want to make a method, which can be executed in the C# interactive on any other pc. Therefore I need a solution that doesn't reference other stuff than the standard (E.g. System, System.Core, ... is allowed).
I do know this is possible with
System.Windows.Forms.Screen.PrimaryScreen.Bounds;
but as this requires the System.Windows.Forms reference, it's not suitable for me. But basically the result of this snippet is what I want to get without references.
Here's an example I came up with.
I have noticed that it does not work correctly on High-DPI Screens. It will report the apparent resolution, not the actual resolution.
static void Main(string[] args)
{
var size = GetScreenSize();
Console.WriteLine(size.Length + " x " + size.Width);
Console.ReadLine();
}
static Size GetScreenSize()
{
return new Size(GetSystemMetrics(0), GetSystemMetrics(1));
}
struct Size
{
public Size(int l, int w)
{
Length = l;
Width = w;
}
public int Length { get; set; }
public int Width { get; set; }
}
[DllImport("User32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern int GetSystemMetrics(int nIndex);
If you don't want to use those libraries, You'll probably need to use native methods. I can't think of a way around this, as you'll need to communicate with the system any way you go.
A good place to start would be the source of System.Windows.Forms.Screen
Here's a link to the source. I bet you could strip down their code, and get the bare minimum.
I actually found a solution to this:
using System;
using System.Runtime.InteropServices;
static void Main()
{
EnumWindows(E, IntPtr.Zero);
Console.Write($"{_.Item1}x{_.Item2}");
}
struct R
{
int l;
int t;
public int r;
public int b;
public override string ToString() => $"{l},{t},{r},{b}";
public bool i() => l == 0 && r != 00;
}
static (int, int) _;
static bool E(IntPtr w, IntPtr l)
{
var r = new R();
GetWindowRect(w, ref r);
if (r.i() && _.Item1 == 0)
_ = (r.r, r.b);
return true;
}
delegate bool P(IntPtr w, IntPtr l);
[DllImport("user32.dll")]
static extern bool EnumWindows(P e, IntPtr l);
[DllImport("user32.dll")]
static extern bool GetWindowRect(IntPtr w, ref R r);
Main()
Paste this into your interactive and it should output the screen resolution - at least it does for me.
Don't ask me how it works, it's stumped together from different tutorials and pressed into the interactive. Therefore I can't guarantee this will work on every pc.
Could somebody else please test this?

How can I position a Win32 floating window inside a user control in my WPF application?

Using a class derived from HwndHost and some voodoo code:
protected override HandleRef BuildWindowCore(HandleRef hwndHost)
{
CheckGuestValidity();
var guestHwnd = new HandleRef(GuestHwnd, _guestHwnd);
Win32.SetWindowStyle(guestHwnd.Handle, WindowStyles.WS_CHILD | Win32.GetWindowStyle(guestHwnd.Handle));
WindowsFormsHost.EnableWindowsFormsInterop();
System.Windows.Forms.Application.EnableVisualStyles();
Win32.SetParent(guestHwnd.Handle, hwndHost.Handle);
Win32.SetWindowStyle(_guestHwnd, Win32.GetWindowStyle(_guestHwnd) & ~WindowStyles.WS_CAPTION);
return guestHwnd;
}
I have managed to get an otherwise parentless (except for Windows' main window) window from a Delphi COM server to adopt my WPF application window as it's parent window. Problem is it is located under all the other user controls etc. at the very bottom of my WPF window. I would like to size and position it to fit inside a rectangle on a tab in a TabControl. How can I go about this? I realise it will take a few resize and position Win32 API calls and maybe even a few low level Windows messages, but I'm up for it.
First I found a handy little class to convert between coordinate systems. It is #Lu55's answer , not the accepted one, to the question How do I convert a WPF size to physical pixels?
Then, my WindowHostView XAML looks like this:
<Grid x:Name="WindowContainer" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="Coral" >
<delphi:Win32WindowHost x:Name="Host" />
</Grid>
The Win32WindowHost class is what contains the code included in my question.
Now I have a neat little routine inside WindowHostView to fit the guest window into the the host's boundarys.
private void PositionGuestWindow(IntPtr hWnd)
{
var rect = WindowContainer.GetAbsoltutePlacement();
var winLeft = Win32Calc.PointsToPixels(rect.Left, Win32Calc.Dimension.Width);
var winTop = Win32Calc.PointsToPixels(rect.Top, Win32Calc.Dimension.Height);
var winWidth = Win32Calc.PointsToPixels(rect.Width, Win32Calc.Dimension.Width);
var winHeight = Win32Calc.PointsToPixels(this.ActualHeight - 20, Win32Calc.Dimension.Height);
Win32Api.MoveWindow(Host.GuestHwnd, (int)winLeft, (int)winTop, (int)winWidth + 1, (int)winHeight, true);
}
And Win32Api.MoveWindow is plain old:
[DllImport("user32.dll", SetLastError = true)]
public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);

Windows forms MenuStrip DropDown inside a desktop application bar

This is a duplicate of a question I posted at Windows Dev Center. Still awaiting replies, so I thought I would try it here. My apologies if the formatting goes awry.
This is currently being written and debugged using Windows 7 Professional, SP1.
The application is located at the top of the desktop, and the working area is appropriately resized via a hook into the SystemParametersInfo function. The MenuStrip appears as it should, with the exception that any dropdown from the MenuStrip shows as detached from the MenuStrip itself (as if it is being drawn on the new working area, as opposed to the form containing the MenuStrip). For example:
Application TopLevel: true
Application Height: 150
Application Location: 0,0 on Desktop (prior to working area's resize)
MenuStrip Height: 25
MenuStrip Location: 0,0 inside Parent Form
MenuStrip DropDown Location: x,2 (where x is a valid and acceptable value) this is being drawn on the resized working area (i.e. beneath the form)
I have attempted correcting this with a custom Renderer to no present avail. I tried to override WndProc (as follows) so as to see what exactly was occurring, but that resulted in a stackoverflow halfway through drawing the application.
protected override void WndProc(ref Message m)
{
if (mainForm.Visible)
{
MessageBox.Show("ID: " + m.Msg.ToString() + "\n" + m.ToString());
}
base.WndProc(ref m);
}
I suspect I've run this into the ground by now, but if you require any further explanation, just let me know. Just hoping someone can point me in the appropriate direction as to where I should look.
Hopefully this will answer the question regarding why I used SystemParametersInfo:
#region TEMPORARY FIX TO ACHIEVE APPBAR
public RECT normalWorkingRECT = new RECT();
public RECT newWorkingRECT = new RECT();
public struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
};
[DllImport("user32.dll", EntryPoint="SystemParametersInfo")]
public static extern bool SystemParametersInfo(uint uiAction, uint uiParam, ref RECT pvParam, uint fWinIni);
//call after scale is set
private void setAppBar()
{
//make the parent = the desktop
if (!this.GetTopLevel())
{
this.SetTopLevel(true);
}
this.Width = SystemInformation.PrimaryMonitorSize.Width;
//set old Working Area
SystemParametersInfo(0x0030, 0, ref normalWorkingRECT, 0);
//change work area based on size of main form
newWorkingRECT.left = normalWorkingRECT.left;
newWorkingRECT.top = normalWorkingRECT.top + this.DesktopBounds.Height + 4;
newWorkingRECT.right = normalWorkingRECT.right;
newWorkingRECT.bottom = normalWorkingRECT.bottom;
SystemParametersInfo(0x002F, 0, ref newWorkingRECT, 0x0002);
}
//called on close
private void unsetAppBar()
{
//get current work area to compare
RECT testRECT = new RECT();
SystemParametersInfo(0x0030, 0, ref testRECT, 0);
//if no change, resize to normal working rect
if (newWorkingRECT.top == testRECT.top &&
newWorkingRECT.bottom == testRECT.bottom &&
newWorkingRECT.left == testRECT.left &&
newWorkingRECT.right == testRECT.right)
{
SystemParametersInfo(0x002F, 0, ref normalWorkingRECT, 0x0002);
}
//if there is a change, resize to current working rect - this.height
else
{
testRECT.top -= this.DesktopBounds.Height + 4;
SystemParametersInfo(0x002F, 0, ref testRECT, 0x0002);
}
}
#endregion
EDIT: Added image as requested and code to show reason for SystemParametersInfo.

Highlight Current Line of RichTextBox

This highlights the entire width of each line by painting a transparent color as the backcolor on the current line. When the line switches, the original background color is restored.
So, what we want to do is:
Verify the previous and current rectangles don't match, so not to paint the same area twice
Replace the last line's highlight using the controls backcolor
Highlight the current line using a transparent color
Set mLastHighlight with the index and rectangle for each applied line
However, when removing the highlight, the text is painted over. This does not occur when applying the highlight.
One solution would be to repaint the text back on the control after resetting the back color. though the text formatting, selection colors, font styles, hyperlinks, etc would be tedious to filter. Not very elegant.
This leads to a simpler solution, refreshing the control. Though that would cause massive flickering. Not acceptable either.
Is there an elegant solution? I'm completely baffled why this occurs.
EDIT: Edited to reflect Code Gray's response.
using System;
public class RTBHL : RichTextBox
{
private LastHighlight mLastHighlight = new LastHighlight(0, Rectangle.Empty);
private class LastHighlight
{
public int mCharIndex;
public Rectangle mRectangle;
public LastHighlight(int index, Rectangle r)
{
mCharIndex = index;
mRectangle = r;
}
}
public void PaintLineHighlight()
{
using (Graphics g = this.CreateGraphics)
{
// highlight color
Color c = Color.Beige;
// current pen color
Pen cp = new Pen(Color.Beige);
// color for removing highlight
Pen lp = new Pen(this.BackColor);
// brush for removing highlight
SolidBrush lb = new SolidBrush(this.BackColor);
// brush for applying highlight
SolidBrush cb = new SolidBrush(Color.FromArgb(64, c.R, c.G, c.B));
// index of the current line
int index = this.GetFirstCharIndexOfCurrentLine;
// rectangle to specify which region to paint too
Rectangle r = new Rectangle();
// specify dimensions
r.X = 0;
r.Y = this.GetPositionFromCharIndex(index).Y;
r.Width = this.HorizontalScrollBarWidth;
r.Height = Convert.ToInt32(this.Font.Height * this.ZoomFactor);
// this will always be true unless the current line remains the same
if (!(mLastHighlight.mCharIndex == index) && !(mLastHighlight.mRectangle == r))
{
// remove the last highlight. regardless of the brush specified, white is always applied, and the text is painted over
g.DrawRectangle(lp, mLastHighlight.mRectangle);
g.FillRectangle(lb, mLastHighlight.mRectangle);
// apply highlight to the current line
g.DrawRectangle(cp, r);
g.FillRectangle(cb, r);
}
mLastHighlight = new LastHighlight(index, r);
}
}
#region RichScrollBars
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetScrollInfo(IntPtr hWnd, int fnBar, ref SCROLLINFO si);
[StructLayout(LayoutKind.Sequential)]
public class SCROLLINFO
{
public int cbSize;
public int fMask;
public int nMin;
public int nMax;
public int nPage;
public int nPos;
public int nTrackPos;
public SCROLLINFO()
{
this.cbSize = Marshal.SizeOf(typeof(SCROLLINFO));
}
public SCROLLINFO(int mask, int min, int max, int page, int pos)
{
this.cbSize = Marshal.SizeOf(typeof(SCROLLINFO));
this.fMask = mask;
this.nMin = min;
this.nMax = max;
this.nPage = page;
this.nPos = pos;
}
}
private const int SIF_ALL = 0X17;
private const int SB_HORZ = 0;
private const int SB_VERT = 1;
public int HorizontalScrollBarWidth()
{
SCROLLINFO si = new SCROLLINFO() {fMask = SIF_ALL};
GetScrollInfo(this.Handle, SB_HORZ, si);
return Math.Max(si.nMax, this.Width);
}
public int VerticalScrollBarHeight()
{
SCROLLINFO si = new SCROLLINFO() {fMask = SIF_ALL};
GetScrollInfo(this.Handle, SB_VERT, si);
return Math.Max(si.nMax, this.Height);
}
#endregion
}
The problem here is that the code you're copying is designed for Scintilla. The SCI_* constants are defined internally by the Scintilla headers, and the messages they refer to only have meaning to the Scintilla controls.
Sending those messages to the native Win32 rich edit control isn't going to do anything because it wasn't designed to process those messages. (Or worse, one or more of the SCI_* constants happen to clash with one or more of the message identifiers that the rich edit control does recognize, producing some potentially interesting behavior.)
Unless you're actually using a Scintilla edit control in your project (which you said you don't want to do), that code isn't going to do anything interesting. It isn't written for the Win32 rich edit control, it's written to interface with the Scintilla control.
The Scintilla control is far more than just a wrapper around the Win32 rich edit control. It has to do a lot of custom drawing to make its magic, and all of that code is hard to get right on your own. That's why so many people use Scintilla in the first place. If you need its feature set, I highly recommend that you follow suit.
Anyway, I don't actually know if this is possible with the Win32 rich edit control. I don't think it is, but I couldn't swear to that fact. I guess you could hack it by setting the selection color, but that doesn't seem like a very good solution. Something like Daniel suggests here. I'm not a Scintilla expert, but to my untrained eyes, this looks kind of like the moral equivalent of your Scintilla-based code, but written for the Win32 rich edit control (through the .NET WinForms wrapper thereof).

How to get mouse position related to desktop in WPF?

Problem
When you search for such question using google you get a lot of hits but all solutions assume you have at least one window.
But my question is just like I phrased it -- not assumptions at all. I can have a window, but I could have zero windows (because I didn't even show one or I just closed the last one). So in short the solution cannot rely on any widget or window -- the only thing is known, is there is a desktop (and app running, but it does not have any windows).
So the question is -- how to get the mouse position?
Background
I would like to show windows centered to mouse position. There is no such mode in WPF (there are only center to owner, or center to screen) so I have to do it manually. The missing piece is mouse position.
Edits
Thank you all, so now I have the first part of the solution -- raw position. Now there is a problem how to convert the data for WPF. I found such topic:
WPF Pixels to desktop pixels
but again, it assumes having some window.
Then I googled more and I found solution:
http://jerryclin.wordpress.com/2007/11/13/creating-non-rectangular-windows-with-interop/
the code includes class for scaling up/down coordinates relying only on info about desktop. So joining those two pieces, I finally get the solution :-). Thanks again.
Getting the Screen Coordinates:
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetCursorPos(out POINT lpPoint);
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int X;
public int Y;
public POINT(int x, int y)
{
this.X = x;
this.Y = y;
}
}
private void WritePoint(object sender, RoutedEventArgs e)
{
POINT p;
if (GetCursorPos(out p))
{
System.Console.WriteLine(Convert.ToString(p.X) + ";" + Convert.ToString(p.Y));
}
}
Converting Pixels to WPF Units:
[DllImport("User32.dll")]
static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("gdi32.dll")]
static extern int GetDeviceCaps(IntPtr hdc, int nIndex);
[DllImport("user32.dll")]
static extern bool ReleaseDC(IntPtr hWnd, IntPtr hDC);
private Point ConvertPixelsToUnits(int x, int y)
{
// get the system DPI
IntPtr dDC = GetDC(IntPtr.Zero); // Get desktop DC
int dpi = GetDeviceCaps(dDC, 88);
bool rv = ReleaseDC(IntPtr.Zero, dDC);
// WPF's physical unit size is calculated by taking the
// "Device-Independant Unit Size" (always 1/96)
// and scaling it by the system DPI
double physicalUnitSize = (1d / 96d) * (double)dpi;
Point wpfUnits = new Point(physicalUnitSize * (double)x,
physicalUnitSize * (double)y);
return wpfUnits;
}
Putting both together:
private void WriteMouseCoordinatesInWPFUnits()
{
POINT p;
if (GetCursorPos(out p))
{
Point wpfPoint = ConvertPixelsToUnits(p.X, p.Y);
System.Console.WriteLine(Convert.ToString(wpfPoint.X) + ";" + Convert.ToString(wpfPoint.Y));
}
}
Two options:
Use System.Windows.Forms.Control.MousePosition, or p/invoke
[DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=true)]
public static extern bool GetCursorPos([In, Out] NativeMethods.POINT pt);
The first option already does the p/invoke for you. I'm not entirely sure it requires you have some UI splashed up, but I don't think so. Yes, its winforms and not wpf, but it really doesn't have anything to do with where its located at.
If you want to skip any dependencies on system.windows.forms.dll then check out more information about the second on pinvoke.net.
I stumbled over that thread while looking for a solution for the same problem. In the meantime, I found PointToScreen, which does not require any P/Invoke. The method is available on any Visual starting .NET 3.0 (and thus UIElement, Control, etc.) and an implementation would look like this:
protected void OnMouseLeave(object Sender, MouseEventArgs e) {
var relativePosition = e.GetPosition(this);
var screenPosition = this.PointToScreen(relativePosition);
}

Categories