When I do this;
Point startpoint = Cursor.Position;
startpoint.Y -= 1;
DoMouse(MOUSEEVENTF.MOVE | MOUSEEVENTF.ABSOLUTE, startpoint);
The mouse doesn't just move up.. it moves a bit to the left as well. But if I do it in a loop, it only moves to the left at the first iteration.
Here is a fully working console program presenting the problem. You have to Add Reference -> .NET -> System.Drawing and System.Windows.Forms to get it to compile.
When starting the program type start to move the mouse up 5 pixels once or type start X (X being a number) to move the mouse up 5 pixels X times. You will see that each new loop the mouse will move a bit to the left; it shouldn't be doing that at all.
using System;
using System.Text.RegularExpressions;
using System.Threading;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace mousemove_temp
{
class Program
{
//Capture user input
static void Main(string[] args)
{
while (true)
{
string s = Console.ReadLine();
switch (s)
{
case("start"):
moveMouseTest(1);
break;
default:
//Get # of times to run function
Match match = Regex.Match(s, #"start (.+)", RegexOptions.IgnoreCase);
if (!match.Success || match.Groups.Count != 2) break;
//Copy # to int
int amnt = -1;
try
{
amnt = Int32.Parse(match.Groups[1].Value);
}
catch (Exception) { break; } //fail
if (amnt <= -1) break; //fail
moveMouseTest(amnt); //aaaawww yeah
break;
}
Thread.Sleep(10);
}
}
//Move the mouse
static void moveMouseTest(int repeat)
{
int countrepeat = 0;
//Loop entire function X times
while (countrepeat < repeat)
{
Point startpoint = Cursor.Position;
int amount = 5; //Move 5 pixels
int counter = 0;
//Move 1 pixel up each loop
while (counter < amount)
{
startpoint.Y -= 1;
DoMouse(MOUSEEVENTF.MOVE | MOUSEEVENTF.ABSOLUTE, startpoint);
counter++;
Thread.Sleep(100); //Slow down so you can see it only jumps left the first time
}
countrepeat++;
Console.WriteLine(String.Format("{0}/{1}", countrepeat, repeat));
Thread.Sleep(1000); //Wait a second before next loop
}
}
/*
* Function stuff
*/
//Control the Mouse
private static object mouselock = new object(); //For use with multithreading
public static void DoMouse(MOUSEEVENTF flags, Point newPoint)
{
lock (mouselock)
{
INPUT input = new INPUT();
MOUSEINPUT mi = new MOUSEINPUT();
input.dwType = InputType.Mouse;
input.mi = mi;
input.mi.dwExtraInfo = IntPtr.Zero;
// mouse co-ords: top left is (0,0), bottom right is (65535, 65535)
// convert screen co-ord to mouse co-ords...
input.mi.dx = newPoint.X * (65535 / Screen.PrimaryScreen.Bounds.Width);
input.mi.dy = newPoint.Y * (65535 / Screen.PrimaryScreen.Bounds.Height);
input.mi.time = 0;
input.mi.mouseData = 0;
// can be used for WHEEL event see msdn
input.mi.dwFlags = flags;
int cbSize = Marshal.SizeOf(typeof(INPUT));
int result = SendInput(1, ref input, cbSize);
if (result == 0)
Console.WriteLine("DoMouse Error:" + Marshal.GetLastWin32Error());
}
}
/*
* Native Methods
*/
[DllImport("user32.dll", SetLastError = true)]
static internal extern Int32 SendInput(Int32 cInputs, ref INPUT pInputs, Int32 cbSize);
[DllImport("user32.dll")]
public static extern bool GetAsyncKeyState(Int32 vKey);
[StructLayout(LayoutKind.Explicit, Pack = 1, Size = 28)]
internal struct INPUT
{
[FieldOffset(0)]
public InputType dwType;
[FieldOffset(4)]
public MOUSEINPUT mi;
[FieldOffset(4)]
public KEYBDINPUT ki;
[FieldOffset(4)]
public HARDWAREINPUT hi;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct MOUSEINPUT
{
public Int32 dx;
public Int32 dy;
public Int32 mouseData;
public MOUSEEVENTF dwFlags;
public Int32 time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct KEYBDINPUT
{
public Int16 wVk;
public Int16 wScan;
public KEYEVENTF dwFlags;
public Int32 time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct HARDWAREINPUT
{
public Int32 uMsg;
public Int16 wParamL;
public Int16 wParamH;
}
internal enum InputType : int
{
Mouse = 0,
Keyboard = 1,
Hardware = 2
}
[Flags()]
internal enum MOUSEEVENTF : int
{
MOVE = 0x1,
LEFTDOWN = 0x2,
LEFTUP = 0x4,
RIGHTDOWN = 0x8,
RIGHTUP = 0x10,
MIDDLEDOWN = 0x20,
MIDDLEUP = 0x40,
XDOWN = 0x80,
XUP = 0x100,
VIRTUALDESK = 0x400,
WHEEL = 0x800,
ABSOLUTE = 0x8000
}
[Flags()]
internal enum KEYEVENTF : int
{
EXTENDEDKEY = 1,
KEYUP = 2,
UNICODE = 4,
SCANCODE = 8
}
}
}
Can anybody tell what's going wrong?
You're doing the math wrong and as a result are getting rounding errors.
For example, 65535 / 1920 = 34.1328125. But truncation (because you are dividing an int by an int) is resulting in 34. So if on a 1920x1080 screen you had the mouse all the way at the right, you would get 1920 * (65535 / 1920) = 1920 * 34 = 65280.
This will get you better results:
input.mi.dx = (int)((65535.0f * (newPoint.X / (float)Screen.PrimaryScreen.Bounds.Width)) + 0.5f);
input.mi.dy = (int)((65535.0f * (newPoint.Y / (float)Screen.PrimaryScreen.Bounds.Height)) + 0.5f);
Though if you're determined to use P/Invoke rather than just say
Cursor.Position = new Point(newPoint.X, newPoint.Y);
then you really should use SetCursorPos - http://msdn.microsoft.com/en-us/library/windows/desktop/ms648394(v=vs.85).aspx - since that (along with GetCursorPos) is the API that .NET is using to get and set the cursor position via Cursor.Position.
Simplest way for your project is useful open-source library Windows Input Simulator (C# SendInput Wrapper - Simulate Keyboard and Mouse) on codeplex. Use it!
Related
I am doing a WinForms application with image/page scheme (the user is navigating between images by clicking at particular areas of the image). At one page I made rich textbox in which I wanted to load "rules" for the user to accept. Unfortunatelly, the rules are longer than the RTB, so I had to apply some kind of scrolling. I didn't want to let the user use a scrollbar - instead I made two buttons (up & down) by which the user can slide through the rules - user cant select or move text in any other way. Everything works great apart from one thing - after clicking the button, the text slides but part of the 1st and last shown lines are being cut (only part of the height of line is visible in rtb).
Below I list the code used for making such RTB (named "rules"):
rules.Clear();
rules.Cursor = Cursors.Default;
rules.ScrollBars = RichTextBoxScrollBars.Vertical;
rules.ReadOnly = true;
rules.KeyPress += rules_KeyPress;
rules.SelectionChanged += rules_SelectionChanged;
rules.Location = new System.Drawing.Point(450*this.Width/2000, 550*this.Height/1125);
Console.WriteLine(rules.Font);
float size = 16.5F;
rules.Font = new Font("Microsoft Sans Serif", size);
Console.WriteLine(rules.Font);
using (Graphics g = rules.CreateGraphics())
{
rules_line_height = Convert.ToInt32(g.MeasureString("A", rules.Font).Height); //getting the measure of the line
Console.WriteLine(rules_line_height);
}
int rules_h = 400 * this.Height / 1125; //height of the rtb
int lines_n = rules_h / rules_line_height; //max number of lines that can be fit in the height
rules.Size = new System.Drawing.Size(1000 * this.Width / 2000, lines_n*rules_line_height); //height of the rtb adjusted to fill full lines
rules.ForeColor = Color.White;
string fileName = "reg_pl.txt";
string line = "";
StreamReader file = new System.IO.StreamReader(Directory.GetCurrentDirectory() + "/reg/" + fileName, Encoding.GetEncoding("windows-1250"));
while ((line = file.ReadLine()) != null)
{
rules.AppendText(line + "\r\n");
}
file.Close();
rules_max = rules.GetMaxRange(); //getting max range of the rtb
rules_thumb = rules.GetThumb(); //getting size of visible part of the rtb
rules_loc = 0; // current location visible part compared to the whole rtb
rules.ScrollBars = RichTextBoxScrollBars.None;
rules.BorderStyle = BorderStyle.None;
rules.BackColor = Color.FromArgb(18, 25, 56);
rules.BringToFront();
I also used the custom_RTB class for getting max range and thumb of the RTB and scrolling to selected point of the RTB :
public class CustomRTB : System.Windows.Forms.RichTextBox
{
#region API Stuff
public struct SCROLLINFO
{
public int cbSize;
public int fMask;
public int min;
public int max;
public int nPage;
public int nPos;
public int nTrackPos;
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int GetScrollPos(IntPtr hWnd, int nBar);
[DllImport("user32.dll")]
private static extern int SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw);
[DllImport("User32.Dll", EntryPoint = "PostMessageA")]
static extern bool PostMessage(IntPtr hWnd, uint msg, int wParam, int lParam);
[DllImport("user32")]
private static extern int GetScrollInfo(IntPtr hwnd, int nBar,
ref SCROLLINFO scrollInfo);
private const int SB_HORZ = 0x0;
private const int SB_VERT = 0x1;
#endregion
public int HorizontalPosition
{
get { return GetScrollPos((IntPtr)this.Handle, SB_HORZ); }
set { SetScrollPos((IntPtr)this.Handle, SB_HORZ, value, true); }
}
public int VerticalPosition
{
get { return GetScrollPos((IntPtr)this.Handle, SB_VERT); }
set { SetScrollPos((IntPtr)this.Handle, SB_VERT, value, true); }
}
public void ScrollTo(int Position)
{
SetScrollPos((IntPtr)this.Handle, 0x1, Position, true);
PostMessage((IntPtr)this.Handle, 0x115, 4 + 0x10000 * Position, 0);
}
public int GetMaxRange()
{
SCROLLINFO scrollInfo = new SCROLLINFO();
scrollInfo.cbSize = Marshal.SizeOf(scrollInfo);
//SIF_RANGE = 0x1, SIF_TRACKPOS = 0x10, SIF_PAGE= 0x2
scrollInfo.fMask = 0x10 | 0x1 | 0x2;
GetScrollInfo((IntPtr)this.Handle, 1, ref scrollInfo);//nBar = 1 -> VScrollbar
return scrollInfo.max;
}
public int GetThumb()
{
SCROLLINFO scrollInfo = new SCROLLINFO();
scrollInfo.cbSize = Marshal.SizeOf(scrollInfo);
//SIF_RANGE = 0x1, SIF_TRACKPOS = 0x10, SIF_PAGE= 0x2
scrollInfo.fMask = 0x10 | 0x1 | 0x2;
GetScrollInfo((IntPtr)this.Handle, 1, ref scrollInfo);//nBar = 1 -> VScrollbar
return scrollInfo.nPage;
}
public int GetCurPos()
{
SCROLLINFO scrollInfo = new SCROLLINFO();
scrollInfo.cbSize = Marshal.SizeOf(scrollInfo);
//SIF_RANGE = 0x1, SIF_TRACKPOS = 0x10, SIF_PAGE= 0x2
scrollInfo.fMask = 0x10 | 0x1 | 0x2;
GetScrollInfo((IntPtr)this.Handle, 1, ref scrollInfo);//nBar = 1 -> VScrollbar
return scrollInfo.nTrackPos;
}
public bool ReachedBottom()
{
SCROLLINFO scrollInfo = new SCROLLINFO();
scrollInfo.cbSize = Marshal.SizeOf(scrollInfo);
//SIF_RANGE = 0x1, SIF_TRACKPOS = 0x10, SIF_PAGE= 0x2
scrollInfo.fMask = 0x10 | 0x1 | 0x2;
GetScrollInfo((IntPtr)this.Handle, 1, ref scrollInfo);//nBar = 1 -> VScrollbar
return scrollInfo.max == scrollInfo.nTrackPos + scrollInfo.nPage;
}
}
And here are the "buttons" for moving the text up:
int lines = rules_thumb / rules_line_height; //getting max number of lines that can be visible
int new_thumb = lines * rules_line_height; //getting the move value so the lines won't be cut
if (rules_loc - (new_thumb) >= 0) //if moving by the move value will be still over 0, then proceed normally
{
rules_loc -= (new_thumb);
rules.ScrollTo(rules_loc);
}
else // if it will pass 0, the move to 0
{
rules_loc = 0;
rules.ScrollTo(rules_loc);
}
And down :
int lines = rules_thumb / rules_line_height;
int new_thumb = lines * rules_line_height;
if (rules_loc + (new_thumb) < rules_max)
{
rules_loc += (new_thumb);
rules.ScrollTo(rules_loc);
}
else
{
rules.ScrollTo(rules_max);
}
What I think I am doing wrong is measuring the lines heigh at given font and setting the good size for the RTB. Does anyone had similar problem and can somehow assist me with it?
Thank you in advance for the answer.
Best regards,
Sarachiel
Mouse stimulation using SendInput works perfectly on MainDisplay. However when I use SendInput for extended screen (e.g. Second screen placed to the left of the main display in my case. Issues is replicable irrespective of the extended display any place around main display but with different resolution then main display):
If I use SendInput on extended screen, the mouse position has offset in both X and Y position, ever so slightly ranging from 40 to 80 points in x and 10 to 20 points in Y based on if X (width) and Y(height) of extended screen is different to main display width/height)
Thanks in advance for any support as to why difference on extended screen
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetCursorPos(ref Win32Point pt);
[DllImport("user32.dll")]
internal static extern bool SetCursorPos(int X, int Y);
[StructLayout(LayoutKind.Sequential)]
internal struct Win32Point
{
public Int32 X;
public Int32 Y;
};
internal enum SendInputEventType : int
{
InputMouse,
InputKeyboard
}
[DllImport("user32.dll", SetLastError = true)]
private static extern uint SendInput(uint nInputs, ref Input pInputs, int cbSize);
public struct Input
{
public uint InputType;
public MouseInput MI;
}
public struct MouseInput
{
public int Dx;
public int Dy;
public uint MouseData;
public uint DwFlags;
public uint Time;
public IntPtr DwExtraInfo;
}
public enum MouseEventInfo
{
mouseEventfMove = 0x0001,
mouseEventfLeftdown = 0x0002,
mouseEventfLeftup = 0x0004,
mouseEventfRightdown = 0x0008,
mouseEventfRightup = 0x0010,
mouseEventfWheel = 0x0800,
mouseEventfAbsolute = 0x8000,
wheelDelta = 0x0078
}
static int CalculateAbsoluteCoordinateX(int x, System.Drawing.Rectangle currentBounds)
{
return ((currentBounds.X + x) * 65536) / (currentBounds.Width);
}
static int CalculateAbsoluteCoordinateY(int y, System.Drawing.Rectangle currentBounds)
{
return (((currentBounds.Y + y) * 65536) / currentBounds.Height);
}
// for me screen at index 0 (screen no 1) is main display. Screen id 2
//placed to the left of the main display as per resolution screen i.e.at
//index 1 (Screen.AllScreens[1]) is extended display and Bound.X is a -ve value
public static int ScreenId = 2;
public static System.Drawing.Rectangle CurrentBounds
{
get
{
return SysForms.Screen.AllScreens[ScreenId - 1].Bounds;
}
}
public static void ClickLeftMouseButton(int x, int y)
{
Input mouseInput = new Input();
mouseInput.InputType = SendInputEventType.InputMouse;
mouseInput.MI.Dx = CalculateAbsoluteCoordinateX(x, CurrentBounds);
mouseInput.MI.Dy = CalculateAbsoluteCoordinateY(y, CurrentBounds);
mouseInput.MI.MouseData = 0;
mouseInput.MI.DwFlags = MouseEventInfo.mouseEventfMove | MouseEventInfo.mouseEventfAbsolute;
SendInput(1, ref mouseInput, Marshal.SizeOf(new INPUT()));
mouseInput.MI.DwFlags = MouseEventInfo.mouseEventfLeftdown;
SendInput(1, ref mouseInput, Marshal.SizeOf(new INPUT()));
mouseInput.MI.DwFlags = MouseEventFlags.mouseEventfLeftup;
SendInput(1, ref mouseInput, Marshal.SizeOf(new INPUT()));
}
//Below is code of the WPF MainWindow for testing. Two buttons with click event.
// For main display with screenid as 1 both setcursor position and sendinput
//work perfectly, as I get the MousePosition, but when I apply this to
//extended screen (currently with two screen, main display is screen 1 in my
//case and screen 2 is extended screen, they put the mouse at two different positions.
//I have my doubts the way I am using the extended screen Bounds.X, but
//haven't will able to fix the issue
int x = 600;
int y = 300;
private void btnSend_Click(object sender, RoutedEventArgs e)
{
SetCursorPos(SysForms.Screen.AllScreens[ScreenId - 1].Bounds.X + x, SysForms.Screen.AllScreens[screenId - 1].Bounds.Y + y);
}
private void btnSend1_Click(object sender, RoutedEventArgs e)
{
ClickLeftMouseButton(x, y);
}
Found the issue. While using SendInput, the conversion of x,y in absolute value must be done in relation to Main/Primary screen.
Thus the changes:
static int CalculateAbsoluteCoordinateX(int x, System.Drawing.Rectangle currentBounds)
{
return ((currentBounds.X + x) * 65536) / (SystemParameters.PrimaryScreenWidth);
}
static int CalculateAbsoluteCoordinateY(int y, System.Drawing.Rectangle currentBounds)
{
return (((currentBounds.Y + y) * 65536) / SystemParameters.PrimaryScreenHeight);
}
I am writing a c# console tetris game. Once I got to the part that the application was ready. I got to the part where I had to solve lagging. I am writing out like this:
static void writeCol(string a, ConsoleColor b)
{
ConsoleColor c = Console.ForegroundColor;
Console.ForegroundColor = b;
Console.Write(a);
Console.ForegroundColor = c;
}
So when a new block comes/i want to move somehing:
writeCol(blokk, ConsoleColor.Magenta);
Where blokk is:
private const string blokk = "█";
I have found a way to "write" to the console faster:
using System;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
namespace ConsoleApplication1
{
class Program
{
[DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern SafeFileHandle CreateFile(
string fileName,
[MarshalAs(UnmanagedType.U4)] uint fileAccess,
[MarshalAs(UnmanagedType.U4)] uint fileShare,
IntPtr securityAttributes,
[MarshalAs(UnmanagedType.U4)] FileMode creationDisposition,
[MarshalAs(UnmanagedType.U4)] int flags,
IntPtr template);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool WriteConsoleOutput(
SafeFileHandle hConsoleOutput,
CharInfo[] lpBuffer,
Coord dwBufferSize,
Coord dwBufferCoord,
ref SmallRect lpWriteRegion);
[StructLayout(LayoutKind.Sequential)]
public struct Coord
{
public short X;
public short Y;
public Coord(short X, short Y)
{
this.X = X;
this.Y = Y;
}
};
[StructLayout(LayoutKind.Explicit)]
public struct CharUnion
{
[FieldOffset(0)] public char UnicodeChar;
[FieldOffset(0)] public byte AsciiChar;
}
[StructLayout(LayoutKind.Explicit)]
public struct CharInfo
{
[FieldOffset(0)] public CharUnion Char;
[FieldOffset(2)] public short Attributes;
}
[StructLayout(LayoutKind.Sequential)]
public struct SmallRect
{
public short Left;
public short Top;
public short Right;
public short Bottom;
}
[STAThread]
static void Main(string[] args)
{
SafeFileHandle h = CreateFile("CONOUT$", 0x40000000, 2, IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero);
if (!h.IsInvalid)
{
CharInfo[] buf = new CharInfo[80 * 25];
SmallRect rect = new SmallRect() { Left = 0, Top = 0, Right = 80, Bottom = 25 };
for (byte character = 65; character < 65 + 26; ++character)
{
for (short attribute = 0; attribute < 15; ++attribute)
{
for (int i = 0; i < buf.Length; ++i)
{
buf[i].Attributes = attribute;
buf[i].Char.AsciiChar = character;
}
bool b = WriteConsoleOutput(h, buf,
new Coord() { X = 80, Y = 25 },
new Coord() { X = 0, Y = 0 },
ref rect);
}
}
}
Console.ReadKey();
}
}
}
(This code prints out all the characters from A-Z).
So finnaly the question:
How can i modify this code to take advantage of it?
Thanks in advance. Have a nice day.
EDIT:
I found 1 way but it gives me buggy text. Any ideas?
public static void Writetocol(string s)
{
var kiir = s;
byte[] barr;
kiir = Convert.ToString(kiir);
barr = Encoding.ASCII.GetBytes(kiir);
SafeFileHandle h = CreateFile("CONOUT$", 0x40000000, 2, IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero);
if (!h.IsInvalid)
{
CharInfo[] buf = new CharInfo[80 * 25];
SmallRect rect = new SmallRect() { Left = 0, Top = 0, Right = 80, Bottom = 25 };
for (short attribute = 0; attribute < 15; ++attribute)
{
for (int i = 0; i < barr.Length; ++i)
{
buf[i].Attributes = attribute;
buf[i].Char.AsciiChar = barr[i];
}
bool b = WriteConsoleOutput(h, buf,
new Coord() { X = 80, Y = 25 },
new Coord() { X = 0, Y = 0 },
ref rect);
}
}
}
It gives me this:
When it should give me this:
(It's written Hungarian if anyone wonders)
You could parse the string you provide to fill the buffer by handling your own linefeeds and position, like so:
static void writeCol(string a, ConsoleColor b)
{
byte x = 0, y = 0;
// parsing to make it fly
// fill the buffer with the string
for(int ci=0; ci<a.Length;ci++)
{
switch (a[ci])
{
case '\n': // newline char, move to next line, aka y=y+1
y++;
break;
case '\r': // carriage return, aka back to start of line
x = 0;
break;
case ' ': // a space, move the cursor to the right
x++;
break;
default:
// calculate where we should be in the buffer
int i = y * 80 + x;
// color
buf[i].Attributes= (short) b;
// put the current char from the string in the buffer
buf[i].Char.AsciiChar = (byte) a[ci];
x++;
break;
}
}
// we handled our string, let's write the whole screen at once
bool success = WriteConsoleOutput(h, buf,
new Coord() { X = 80, Y = 25 },
new Coord() { X = 0, Y = 0 },
ref rect);
}
Notice that I already refactored the safehandle h and the native buffer buf to the static state so we only have this once in the app:
static IntPtr h= GetStdHandle(STD_OUTPUT_HANDLE);
static CharInfo[] buf = new CharInfo[80 * 25];
static SmallRect rect = new SmallRect() { Left = 0, Top = 0, Right = 80, Bottom = 25 };
I have added the GetStdHandle
//http://www.pinvoke.net/default.aspx/kernel32/GetStdHandle.html
const int STD_OUTPUT_HANDLE = -11;
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr GetStdHandle(int nStdHandle);
You need to change the method signature on WriteConsoleOutput to accept an IntPtr instead of SafeFileHandle in that case.
I tested this method with the following test call:
writeCol(#"
TEST
======
1 test
FuBar", ConsoleColor.Blue);
which gives this result:
So keep in mind to fill the buffer buf at the correct positions first and then call WriteConsoleOutput to copy the buffer to the screen at once. If you call that very often you are back to square one...
Notice that you don't need to write the whole screen. By using different rectangles you can write only parts of the screen.
For this demo I left out all error-checking. That is up to you to check.
You might want to read up on the native calls used from the msdn documentation
how can I write DIRECTLY into console, without bothering with stdout in c#? I'm upgrading some old program, which has it's stdout redirected into file (because the output matters), and I need somehow to write directly to console, and that the text won't appear in stdout. Is it possible (without using WinAPI)?
EDIT: I'm aware of the possibility to write to stderr, althrough, is it possible to set cursor position for stderr on console?
You could write to Console.Error, which, although it can be redirected, is separate from stdout.
is it possible to set cursor position for stderr on console?
Edit: Assuming that stderr has not been redirected, see Console.CursorTop and Console.CursorLeft. There's various other members on the Console class that you might find useful.
To answer your question directly, use the Win32 WriteConsole function. As far as I can see, the .NET framework doesn't have methods for writing directly to the console window.
If I run your program and redirect its StandardOutput and StandardError, what do you expect to happen to your writes when there is no console?
For this reason, the answer is likely “you can’t” (except perhaps by using crazy hacks, which probably involve Windows API which you said you didn’t want to use).
Think of the console window as nothing more than a UI element that allows the user to view the stdout/stderr of your program (and to provide stdin). It doesn’t really exist for any other purpose.
I actually ended up implementing the low level WriteConsoleOutput some time ago as part of a terminal based Tetris implementation I wrote, since doing coloured console output with Console.BackgroundColor and Console.Write, is far too slow for full screen refreshes. Doing the raw buffer output is much faster.
Note, this writes text to a location on the screen (eg 5,10), but doesn't update or keep track of the cursor position on it's own - writing with this method will update the text buffer and display the output, but the cursor won't move. You'll need to move and keep track of the console cursor manually with some other method, which shouldn't be too difficult.
Here's my code:
Main interop class:
public static class LowLevelConsole {
[DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern SafeFileHandle CreateFile(
string fileName,
[MarshalAs(UnmanagedType.U4)] uint fileAccess,
[MarshalAs(UnmanagedType.U4)] uint fileShare,
IntPtr securityAttributes,
[MarshalAs(UnmanagedType.U4)] FileMode creationDisposition,
[MarshalAs(UnmanagedType.U4)] int flags,
IntPtr template);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool WriteConsoleOutput(
SafeFileHandle hConsoleOutput,
CharInfo[] lpBuffer,
Coord dwBufferSize,
Coord dwBufferCoord,
ref SmallRect lpWriteRegion);
[StructLayout(LayoutKind.Sequential)]
public struct Coord {
public short X;
public short Y;
public Coord(short X, short Y) {
this.X = X;
this.Y = Y;
}
};
[StructLayout(LayoutKind.Explicit)]
public struct CharUnion {
[FieldOffset(0)]
public char UnicodeChar;
[FieldOffset(0)]
public byte AsciiChar;
}
[StructLayout(LayoutKind.Explicit)]
public struct CharInfo {
[FieldOffset(0)]
public CharUnion Char;
[FieldOffset(2)]
public ushort Attributes;
}
[StructLayout(LayoutKind.Sequential)]
public struct SmallRect {
public short Left;
public short Top;
public short Right;
public short Bottom;
}
[STAThread]
public static void Write(string line, CharacterAttribute attribute, short xLoc, short yLoc) {
SafeFileHandle h = CreateFile("CONOUT$", 0x40000000, 2, IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero);
short writeHeight = 1;
short writeWidth = (short)line.Length;
if (!h.IsInvalid) {
CharInfo[] buf = new CharInfo[writeWidth * writeHeight];
SmallRect rect = new SmallRect() { Left = xLoc, Top = yLoc, Right = (short)(writeWidth + xLoc), Bottom = (short)(writeHeight + yLoc) };
for (int i = 0; i < writeWidth; i++) {
buf[i].Attributes = (ushort)attribute;
buf[i].Char.UnicodeChar = line[i];
}
bool b = WriteConsoleOutput(h, buf, new Coord() { X = writeWidth, Y = writeHeight }, new Coord() { X = 0, Y = 0 }, ref rect);
}
}
[STAThread]
public static bool WriteBuffer(CharInfo[,] buffer) { // returns true of success
SafeFileHandle h = CreateFile("CONOUT$", 0x40000000, 2, IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero);
if (!h.IsInvalid) {
short BufferWidth = (short)buffer.GetLength(0);
short BufferHeight = (short)buffer.GetLength(1);
CharInfo[] buf = new CharInfo[BufferWidth * BufferHeight];
SmallRect rect = new SmallRect() { Left = 0, Top = 0, Right = BufferWidth, Bottom = BufferHeight };
for (int y = 0; y < BufferHeight; y++) {
for (int x = 0; x < BufferWidth; x++) {
buf[y * BufferWidth + x] = buffer[x, y];
}
}
return WriteConsoleOutput(h, buf, new Coord() { X = BufferWidth, Y = BufferHeight }, new Coord() { X = 0, Y = 0 }, ref rect);
}
return false;
}
}
Character attributes:
[Flags]
public enum CharacterAttribute : ushort {
FOREGROUND_BLUE = 0x0001,
FOREGROUND_GREEN = 0x0002,
FOREGROUND_RED = 0x0004,
FOREGROUND_INTENSITY = 0x0008,
BACKGROUND_BLUE = 0x0010,
BACKGROUND_GREEN = 0x0020,
BACKGROUND_RED = 0x0040,
BACKGROUND_INTENSITY = 0x0080,
COMMON_LVB_LEADING_BYTE = 0x0100,
COMMON_LVB_TRAILING_BYTE = 0x0200,
COMMON_LVB_GRID_HORIZONTAL = 0x0400,
COMMON_LVB_GRID_LVERTICAL = 0x0800,
COMMON_LVB_GRID_RVERTICAL = 0x1000,
COMMON_LVB_REVERSE_VIDEO = 0x4000,
COMMON_LVB_UNDERSCORE = 0x8000
}
Test code:
class Program {
static void Main(string[] args) {
// write to location 0,0
LowLevelConsole.Write("Some test text", CharacterAttribute.BACKGROUND_BLUE | CharacterAttribute.FOREGROUND_RED, 0, 0);
// write to location 5,10
LowLevelConsole.Write("another test at a different location",
CharacterAttribute.FOREGROUND_GREEN | CharacterAttribute.FOREGROUND_BLUE,
5, 10);
Console.ReadLine();
}
}
I want to know how to get the rectangle (bottom, top, left, and right) that the taskbar occupies. How do I go about doing this in C#?
private enum TaskBarLocation { TOP, BOTTOM, LEFT, RIGHT}
private TaskBarLocation GetTaskBarLocation()
{
TaskBarLocation taskBarLocation = TaskBarLocation.BOTTOM;
bool taskBarOnTopOrBottom = (Screen.PrimaryScreen.WorkingArea.Width == Screen.PrimaryScreen.Bounds.Width);
if (taskBarOnTopOrBottom)
{
if (Screen.PrimaryScreen.WorkingArea.Top > 0) taskBarLocation = TaskBarLocation.TOP;
}
else
{
if (Screen.PrimaryScreen.WorkingArea.Left > 0)
{
taskBarLocation = TaskBarLocation.LEFT;
}
else
{
taskBarLocation = TaskBarLocation.RIGHT;
}
}
return taskBarLocation;
}
It's actually way more complicated than is shown above. For one thing, the task bar doesn't have to be on the primary screen, it can be dragged to any screen. For another, in theory there could be something docked on each edge of each given screen. The code above incorrectly assumes that finding something docked to one edge excludes all other edges.
The only way the location of the task bar could be definitively derived from bounds vs workingarea, would be if only one edge out of all screens had something docked to it.
The following function returns an array of Rectangles, each representing a docked task bar, and writes the count to its byref parameter. If that count is 1, element 0 of the returned array is the Rectangle occupied by the task bar. If greater than 1, time to guess?
Public Function FindDockedTaskBars(ByRef DockedRectCounter As Integer) As Rectangle()
Dim TmpScrn As Screen = Nothing
Dim LeftDockedWidth As Integer = 0
Dim TopDockedHeight As Integer = 0
Dim RightDockedWidth As Integer = 0
Dim BottomDockedHeight As Integer = 0
Dim DockedRects(Screen.AllScreens.Count * 4) As Rectangle
DockedRectCounter = 0
For Each TmpScrn In Screen.AllScreens
If Not TmpScrn.Bounds.Equals(TmpScrn.WorkingArea) Then
LeftDockedWidth = Math.Abs(Math.Abs(TmpScrn.Bounds.Left) - Math.Abs(TmpScrn.WorkingArea.Left))
TopDockedHeight = Math.Abs(Math.Abs(TmpScrn.Bounds.Top) - Math.Abs(TmpScrn.WorkingArea.Top))
RightDockedWidth = (TmpScrn.Bounds.Width - LeftDockedWidth) - TmpScrn.WorkingArea.Width
BottomDockedHeight = (TmpScrn.Bounds.Height - TopDockedHeight) - TmpScrn.WorkingArea.Height
If LeftDockedWidth > 0 Then
DockedRects(DockedRectCounter).X = TmpScrn.Bounds.Left
DockedRects(DockedRectCounter).Y = TmpScrn.Bounds.Top
DockedRects(DockedRectCounter).Width = LeftDockedWidth
DockedRects(DockedRectCounter).Height = TmpScrn.Bounds.Height
DockedRectCounter += 1
End If
If RightDockedWidth > 0 Then
DockedRects(DockedRectCounter).X = TmpScrn.WorkingArea.Right
DockedRects(DockedRectCounter).Y = TmpScrn.Bounds.Top
DockedRects(DockedRectCounter).Width = RightDockedWidth
DockedRects(DockedRectCounter).Height = TmpScrn.Bounds.Height
DockedRectCounter += 1
End If
If TopDockedHeight > 0 Then
DockedRects(DockedRectCounter).X = TmpScrn.WorkingArea.Left
DockedRects(DockedRectCounter).Y = TmpScrn.Bounds.Top
DockedRects(DockedRectCounter).Width = TmpScrn.WorkingArea.Width
DockedRects(DockedRectCounter).Height = TopDockedHeight
DockedRectCounter += 1
End If
If BottomDockedHeight > 0 Then
DockedRects(DockedRectCounter).X = TmpScrn.WorkingArea.Left
DockedRects(DockedRectCounter).Y = TmpScrn.WorkingArea.Bottom
DockedRects(DockedRectCounter).Width = TmpScrn.WorkingArea.Width
DockedRects(DockedRectCounter).Height = BottomDockedHeight
DockedRectCounter += 1
End If
End If
Next
Return DockedRects
End Function
Or for those of you who prefer C#... (Note: this ported code is untested)
using System.Drawing;
using System.Windows.Forms;
public Rectangle[] FindDockedTaskBars(ref int DockedRectCounter)
{
int LeftDockedWidth = 0;
int TopDockedHeight = 0;
int RightDockedWidth = 0;
int BottomDockedHeight = 0;
Rectangle[] DockedRects = new Rectangle[Screen.AllScreens.Count() * 4];
DockedRectCounter = 0;
foreach (Screen TmpScrn in Screen.AllScreens)
{
if (!TmpScrn.Bounds.Equals(TmpScrn.WorkingArea))
{
LeftDockedWidth = Math.Abs(Math.Abs(TmpScrn.Bounds.Left) - Math.Abs(TmpScrn.WorkingArea.Left));
TopDockedHeight = Math.Abs(Math.Abs(TmpScrn.Bounds.Top) - Math.Abs(TmpScrn.WorkingArea.Top));
RightDockedWidth = (TmpScrn.Bounds.Width - LeftDockedWidth) - TmpScrn.WorkingArea.Width;
BottomDockedHeight = (TmpScrn.Bounds.Height - TopDockedHeight) - TmpScrn.WorkingArea.Height;
if (LeftDockedWidth > 0)
{
DockedRects[DockedRectCounter].X = TmpScrn.Bounds.Left;
DockedRects[DockedRectCounter].Y = TmpScrn.Bounds.Top;
DockedRects[DockedRectCounter].Width = LeftDockedWidth;
DockedRects[DockedRectCounter].Height = TmpScrn.Bounds.Height;
DockedRectCounter += 1;
}
if (RightDockedWidth > 0)
{
DockedRects[DockedRectCounter].X = TmpScrn.WorkingArea.Right;
DockedRects[DockedRectCounter].Y = TmpScrn.Bounds.Top;
DockedRects[DockedRectCounter].Width = RightDockedWidth;
DockedRects[DockedRectCounter].Height = TmpScrn.Bounds.Height;
DockedRectCounter += 1;
}
if (TopDockedHeight > 0)
{
DockedRects[DockedRectCounter].X = TmpScrn.WorkingArea.Left;
DockedRects[DockedRectCounter].Y = TmpScrn.Bounds.Top;
DockedRects[DockedRectCounter].Width = TmpScrn.WorkingArea.Width;
DockedRects[DockedRectCounter].Height = TopDockedHeight;
DockedRectCounter += 1;
}
if (BottomDockedHeight > 0)
{
DockedRects[DockedRectCounter].X = TmpScrn.WorkingArea.Left;
DockedRects[DockedRectCounter].Y = TmpScrn.WorkingArea.Bottom;
DockedRects[DockedRectCounter].Width = TmpScrn.WorkingArea.Width;
DockedRects[DockedRectCounter].Height = BottomDockedHeight;
DockedRectCounter += 1;
}
}
}
return DockedRects;
}
Based on David's answer, here is a better implementation that uses P/Invoke to correctly determine the placement and size of the taskbar. The only limitation I know of so far is that it does not return the correct bounds when multiple monitors are set to display in extended mode.
The code with all subsequent updates is available as a gist at https://git.io/v9bCx.
/******************************************************************************
* Name: Taskbar.cs
* Description: Class to get the taskbar's position, size and other properties.
* Author: Franz Alex Gaisie-Essilfie
* based on code from https://winsharp93.wordpress.com/2009/06/29/find-out-size-and-position-of-the-taskbar/
*
* Change Log:
* Date | Description
* -------------|--------------------------------------------------------------
* 2017-05-16 | Initial design
*/
using System;
using System.Drawing;
using System.Runtime.InteropServices;
namespace System.Windows.Forms
{
public enum TaskbarPosition
{
Unknown = -1,
Left,
Top,
Right,
Bottom,
}
public static class Taskbar
{
private enum ABS
{
AutoHide = 0x01,
AlwaysOnTop = 0x02,
}
////private enum ABE : uint
private enum AppBarEdge : uint
{
Left = 0,
Top = 1,
Right = 2,
Bottom = 3
}
////private enum ABM : uint
private enum AppBarMessage : uint
{
New = 0x00000000,
Remove = 0x00000001,
QueryPos = 0x00000002,
SetPos = 0x00000003,
GetState = 0x00000004,
GetTaskbarPos = 0x00000005,
Activate = 0x00000006,
GetAutoHideBar = 0x00000007,
SetAutoHideBar = 0x00000008,
WindowPosChanged = 0x00000009,
SetState = 0x0000000A,
}
private const string ClassName = "Shell_TrayWnd";
private static APPBARDATA _appBarData;
/// <summary>Static initializer of the <see cref="Taskbar" /> class.</summary>
static Taskbar()
{
_appBarData = new APPBARDATA
{
cbSize = (uint)Marshal.SizeOf(typeof(APPBARDATA)),
hWnd = FindWindow(Taskbar.ClassName, null)
};
}
/// <summary>
/// Gets a value indicating whether the taskbar is always on top of other windows.
/// </summary>
/// <value><c>true</c> if the taskbar is always on top of other windows; otherwise, <c>false</c>.</value>
/// <remarks>This property always returns <c>false</c> on Windows 7 and newer.</remarks>
public static bool AlwaysOnTop
{
get
{
int state = SHAppBarMessage(AppBarMessage.GetState, ref _appBarData).ToInt32();
return ((ABS)state).HasFlag(ABS.AlwaysOnTop);
}
}
/// <summary>
/// Gets a value indicating whether the taskbar is automatically hidden when inactive.
/// </summary>
/// <value><c>true</c> if the taskbar is set to auto-hide is enabled; otherwise, <c>false</c>.</value>
public static bool AutoHide
{
get
{
int state = SHAppBarMessage(AppBarMessage.GetState, ref _appBarData).ToInt32();
return ((ABS)state).HasFlag(ABS.AutoHide);
}
}
/// <summary>Gets the current display bounds of the taskbar.</summary>
public static Rectangle CurrentBounds
{
get
{
var rect = new RECT();
if (GetWindowRect(Handle, ref rect))
return Rectangle.FromLTRB(rect.Left, rect.Top, rect.Right, rect.Bottom);
return Rectangle.Empty;
}
}
/// <summary>Gets the display bounds when the taskbar is fully visible.</summary>
public static Rectangle DisplayBounds
{
get
{
if (RefreshBoundsAndPosition())
return Rectangle.FromLTRB(_appBarData.rect.Left,
_appBarData.rect.Top,
_appBarData.rect.Right,
_appBarData.rect.Bottom);
return CurrentBounds;
}
}
/// <summary>Gets the taskbar's window handle.</summary>
public static IntPtr Handle
{
get { return _appBarData.hWnd; }
}
/// <summary>Gets the taskbar's position on the screen.</summary>
public static TaskbarPosition Position
{
get
{
if (RefreshBoundsAndPosition())
return (TaskbarPosition)_appBarData.uEdge;
return TaskbarPosition.Unknown;
}
}
/// <summary>Hides the taskbar.</summary>
public static void Hide()
{
const int SW_HIDE = 0;
ShowWindow(Handle, SW_HIDE);
}
/// <summary>Shows the taskbar.</summary>
public static void Show()
{
const int SW_SHOW = 1;
ShowWindow(Handle, SW_SHOW);
}
private static bool RefreshBoundsAndPosition()
{
//! SHAppBarMessage returns IntPtr.Zero **if it fails**
return SHAppBarMessage(AppBarMessage.GetTaskbarPos, ref _appBarData) != IntPtr.Zero;
}
#region DllImports
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);
[DllImport("shell32.dll", SetLastError = true)]
private static extern IntPtr SHAppBarMessage(AppBarMessage dwMessage, [In] ref APPBARDATA pData);
[DllImport("user32.dll")]
private static extern int ShowWindow(IntPtr hwnd, int command);
#endregion DllImports
[StructLayout(LayoutKind.Sequential)]
private struct APPBARDATA
{
public uint cbSize;
public IntPtr hWnd;
public uint uCallbackMessage;
public AppBarEdge uEdge;
public RECT rect;
public int lParam;
}
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
}
}
private enum TaskBarLocation { TOP, BOTTOM, LEFT, RIGHT }
private TaskBarLocation GetTaskBarLocation()
{
//System.Windows.SystemParameters....
if (SystemParameters.WorkArea.Left > 0)
return TaskBarLocation.LEFT;
if (SystemParameters.WorkArea.Top > 0)
return TaskBarLocation.TOP;
if (SystemParameters.WorkArea.Left == 0
&& SystemParameters.WorkArea.Width < SystemParameters.PrimaryScreenWidth)
return TaskBarLocation.RIGHT;
return TaskBarLocation.BOTTOM;
}
This is the answer from Mark McGinty in C#.
This code brings back all of the task bars as a list of rectanges:
0 rectangles means the taskbar is hidden;
1 rectangle is the position of the taskbar;
2+ is very rare, it means that we have multiple monitors, and we are not using Extend these displays to create a single virtual desktop.
Works in every situation
It works well with:
Windows 7 (will almost certainly work on Windows 8.1 and Windows 10).
All combinations of settings.
C# Code
public static List<Rectangle> FindDockedTaskBars()
{
List<Rectangle> dockedRects = new List<Rectangle>();
foreach (var tmpScrn in Screen.AllScreens)
{
if (!tmpScrn.Bounds.Equals(tmpScrn.WorkingArea))
{
Rectangle rect = new Rectangle();
var leftDockedWidth = Math.Abs((Math.Abs(tmpScrn.Bounds.Left) - Math.Abs(tmpScrn.WorkingArea.Left)));
var topDockedHeight = Math.Abs((Math.Abs(tmpScrn.Bounds.Top) - Math.Abs(tmpScrn.WorkingArea.Top)));
var rightDockedWidth = ((tmpScrn.Bounds.Width - leftDockedWidth) - tmpScrn.WorkingArea.Width);
var bottomDockedHeight = ((tmpScrn.Bounds.Height - topDockedHeight) - tmpScrn.WorkingArea.Height);
if ((leftDockedWidth > 0))
{
rect.X = tmpScrn.Bounds.Left;
rect.Y = tmpScrn.Bounds.Top;
rect.Width = leftDockedWidth;
rect.Height = tmpScrn.Bounds.Height;
}
else if ((rightDockedWidth > 0))
{
rect.X = tmpScrn.WorkingArea.Right;
rect.Y = tmpScrn.Bounds.Top;
rect.Width = rightDockedWidth;
rect.Height = tmpScrn.Bounds.Height;
}
else if ((topDockedHeight > 0))
{
rect.X = tmpScrn.WorkingArea.Left;
rect.Y = tmpScrn.Bounds.Top;
rect.Width = tmpScrn.WorkingArea.Width;
rect.Height = topDockedHeight;
}
else if ((bottomDockedHeight > 0))
{
rect.X = tmpScrn.WorkingArea.Left;
rect.Y = tmpScrn.WorkingArea.Bottom;
rect.Width = tmpScrn.WorkingArea.Width;
rect.Height = bottomDockedHeight;
}
else
{
// Nothing found!
}
dockedRects.Add(rect);
}
}
if (dockedRects.Count == 0)
{
// Taskbar is set to "Auto-Hide".
}
return dockedRects;
}
This is a simple example using winforms with wpf and multi screen support:
Screen sc = Screen.FromHandle(new WindowInteropHelper(this).Handle);
if (sc.WorkingArea.Top > 0)
{
// TASKBAR TOP
}
else if (sc.WorkingArea.Left != sc.Bounds.X)
{
// TASKBAR LEFT
}
else if ((sc.Bounds.Height - sc.WorkingArea.Height) > 0)
{
// TASKBAR BOTTOM
}
else if (sc.WorkingArea.Right != 0)
{
// TASKBAR RIGHT
}
else
{
// TASKBAR NOT FOUND
}
[StructLayout(LayoutKind.Sequential)]
public struct RECT { public Int32 left; public Int32 top; public Int32 right; public Int32 bottom; }
[StructLayout(LayoutKind.Sequential)]
public struct APPBARDATA { public UInt32 cbSize; public IntPtr hWnd; public UInt32 uCallbackMessage; public UInt32 uEdge; public RECT rc; public IntPtr lParam; }
[DllImport("shell32.dll")]
public static extern IntPtr SHAppBarMessage(UInt32 dwMessage, ref APPBARDATA pData);
private void Form1_Load(object sender, EventArgs e)
{
APPBARDATA msgData = new APPBARDATA();
msgData.cbSize = (UInt32)Marshal.SizeOf(msgData);
// get taskbar position
SHAppBarMessage((UInt32)0x00000005, ref msgData);
RECT taskRect = msgData.rc;
Console.WriteLine("top:" + taskRect.top + "; left:" + taskRect.left + "; bottom:" + taskRect.bottom + "; right:" + taskRect.right);
Console.WriteLine("width:" + (taskRect.right - taskRect.left) + "; height:" + (taskRect.bottom - taskRect.top));
}
Output: top:1040; left:0; bottom:1080; right:1920 width:1920;
height:40
This is how to get the Taskbar's Height (using WPF)
int PSBH = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height
int TaskBarHeight = PSBH - System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height;
If you want to account for dpi
int PSH = SystemParameters.PrimaryScreenHeight;
int PSBH = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height;
double ratio = PSH / PSBH;
int TaskBarHeight = PSBH - System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height;
TaskBarHeight *= ratio;
I hate to say this, but one of the best and most consistent methods for setting your window size when using a WindowStyle of none is to create a temporary window that is created, maximized, Width and Height recorded, and then destroyed.
private (double height, double width) GetVirtualWindowSize()
{
Window virtualWindow = new Window();
virtualWindow.Show();
virtualWindow.WindowState = WindowState.Maximized;
double returnHeight = virtualWindow.Height;
double returnWidth = virtualWindow.Width;
virtualWindow.Close();
return (returnHeight, returnWidth);
}
You can then set the MaxHeight and MaxWidth properties of your window using the values returned within the tuple. This "sacrificial" window will use the standard window frame, and so Windows knows how to properly maximize it, thus returning accurate values every time.
You can do this at startup so that you only have to deal with the window creation once, or you can recheck the dimensions on every maximize.
I know it isn't pretty, and there is a brief flash. But it always works for me, no matter where the taskbar is, no matter the scaling, and no matter the changes that have taken place since the application started.
This will work on Windows and macOS. It will also work with multiple monitors. As is, it is for electron applications, but you can easily understand what's going on.
type TaskBarPos int
const (
UNKNOWN TaskBarPos = -1
LEFT TaskBarPos = 0
RIGHT TaskBarPos = 1
TOP TaskBarPos = 2
BOTTOM TaskBarPos = 3
)
type Rect struct {
top int
bottom int
width int
height int
left int
right int
}
func (r Rect) centerX() int {
return r.left + ((r.right - r.left) / 2)
}
func (r Rect) centerY() int {
return r.top + ((r.bottom - r.top) / 2)
}
func taskbar(tray *js.Object) TaskBarPos {
// Step 1 - Get relevant display
display := screen.Call("getDisplayNearestPoint", screen.Call("getCursorScreenPoint")) // Replace with primary monitor or a secondary monitor. This line as is grabs the monitor that the mouse cursor is on.
// Step 2 - Determine taskbar bounds relative to the display
bounds := display.Get("bounds")
workArea := display.Get("workArea")
var tb *Rect
d := Rect{
top: bounds.Get("y").Int(),
bottom: bounds.Get("y").Int() + bounds.Get("height").Int(),
width: bounds.Get("width").Int(),
height: bounds.Get("height").Int(),
left: bounds.Get("x").Int(),
right: bounds.Get("x").Int() + bounds.Get("width").Int(),
}
wa := Rect{
top: workArea.Get("y").Int(),
bottom: workArea.Get("y").Int() + workArea.Get("height").Int(),
width: workArea.Get("width").Int(),
height: workArea.Get("height").Int(),
left: workArea.Get("x").Int(),
right: workArea.Get("x").Int() + workArea.Get("width").Int(),
}
if tray != nil {
tBounds := tray.Call("getBounds")
tb = &Rect{
top: tBounds.Get("y").Int(),
bottom: tBounds.Get("y").Int() + tBounds.Get("height").Int(),
width: tBounds.Get("width").Int(),
height: tBounds.Get("height").Int(),
left: tBounds.Get("x").Int(),
right: tBounds.Get("x").Int() + tBounds.Get("width").Int(),
}
}
// Step 3 - Determine Position of Taskbar
if wa.top > d.top {
return TOP
} else if wa.bottom < d.bottom {
return BOTTOM
} else if wa.left > d.left {
return LEFT
} else if wa.right < d.right {
return RIGHT
}
if tb == nil {
return UNKNOWN
}
// Check which corner tray is closest to
if ((*tb).top - d.top) < (d.bottom - (*tb).bottom) {
return TOP
}
if ((*tb).left - d.left) < (d.right - (*tb).right) {
return LEFT
}
if d.bottom-(*tb).centerY() < d.right-(*tb).centerX() {
return BOTTOM
}
return RIGHT
}