Console application window and buffer sizes in Windows 11 - c#

Okay so I have a console application in Windows 11 using .Net-7.0 and not targeting any particular platform
When I go to set the console's window and buffer sizes it does absolutely nothing, and without checking if the operating system is Windows using OperatingSystem.IsWindows() before calling either Console.SetWindowSize([w], [w]) or Console.SetBufferSize([w], [h]) the IDE throws a warning of CA1416 as it isn't a platform specific call.
I have no problem using the IsWindows() check as this is just a test application, but I am trying to output the data in a fixed width and height (such as a REPL application would, but without redrawing the screen). Since I cannot set either the window width OR the buffer width through the System.Console API I would have to implement my own buffer code to accomplish what I am trying to do.
Is this an issue with Windows Terminal vs CMD? How do I accomplish what I am trying to do without bringing in a third party library? Am I stuck having to do some P/Invoke magic to do this?
EDIT: I am unable to change the framework I am targeting at all as the code this program tests requires .Net-7.0
EDIT 2: Upon further diagnosis I have found that a fresh console app targeting .Net Core 3.1 WILL allow me to set the buffer width/height in the following way, however it does NOT modify the window's size at all and does NOT work in .Net-7.0. Only the buffer is actually adjusted, and the call to Console.Clear() is required to make it actually stick.
Console.SetWindowSize(5,5);
Console.SetBufferSize(5,5);
Console.Clear();

According to Classic Console APIs versus Virtual Terminal Sequences:
Our recommendation is to replace the classic Windows Console API with
virtual terminal sequences. This article will outline the difference
between the two and discuss the reasons for our recommendation.
Definitions The classic Windows Console API surface is defined as the
series of C language functional interfaces on kernel32.dll with
"Console" in the name.
...
Cross-Platform Support
Virtual terminal sequences are natively
supported across platforms, making terminal applications and
command-line utilities easily portable between versions and variations
of operating systems, with the exception of Windows.
By contrast, Windows Console APIs are only supported on Windows. An
extensive adapter or translation library must be written between
Windows and virtual terminal, or vice-versa, when attempting to port
command-line utilities from one platform or another.
In the OP you've specified Windows Console APIs
Console.SetWindowSize
Console.SetBufferSize
but stated that you're not targeting any particular platform which is why you've received the following message:
CA1416: This call site is reachable on all platforms. 'Console.SetBufferSize(int, int)' is only supported on: 'windows'.
and
CA1416: This call site is reachable on all platforms. 'Console.SetWindowSize(int, int)' is only supported on: 'windows'.
Both messages state: only supported on: 'windows', which means that if you want to use them, you need to target Windows.
To Target Windows (VS 2022):
In VS menu, click Project
Select <project name> Properties
Under Target OS, select Windows
Clean and rebuild.
Also see: Target frameworks in SDK-style projects
The following code is adapted from here and has been tested. It works with .NET 7 after setting the Target OS to Windows.
static void Main(string[] args)
{
int width = 80;
int height = 10;
if (Console.WindowLeft + Console.WindowWidth < width && Console.WindowTop + Console.WindowHeight < height)
System.Console.SetBufferSize(width, height);
System.Console.SetWindowSize(width, height);
for (int i = 0; i < height; i++)
{
Console.WriteLine($"line {i + 1}");
}
}
Additional Resources:
Windows Console and Terminal Ecosystem Roadmap
Console Virtual Terminal Sequences
Console Functions
VB.NET Console: Use ANSI Sequences (Console Virtual Terminal Sequences)

Related

Code for copying the text from another window

Is it possible to write a code that will copy text values from a window belonging to another application?
I have an application that gives me live results(only texts), every 5 minutes, and I cannot copy paste them every 5 min.
Maybe.
It depends on how the target application is exposing its text to the OS.
If the application is using a private 2D/drawing library to render text by itself to an in-memory or in-VRAM buffer, then no. You'll need to grab a screenshot and perform OCR on it - or you could inject your own code into the target process and intercept those 2D/drawing library calls to get the text being rendered.
If the application is using the Windows-provided GDI then there are ways of intercepting those calls to get the text. I believe Direct2D and DirectWrite also offer straightforward ways of intercepting/profiling their calls as well.
If the application is using a GUI framework or platform like WinForms or WPF then there are ways of inspecting the rendered view's object-model to extract data and text - this is how various "Spy" utilities work. "Spy++" (spyxx.exe included in Visual Studio and the Windows SDK) can inspect native Win32 hWnd windows and "Snoop" is a very powerful tool for inspecting WPF applications (Visual Studio's built-in Visual Inspector does the same thing).
Additionally, often GUI frameworks and platforms will support the OS' built-in Accessibility platform and will expose on-screen data as machine-readable structured data for use by screen-readers for the blind and visually impaired as well as automation software. Windows' built-in platform is called Active Accessibility and Windows UI Automation. There are premade tools you can download to inspect Active Accessibility data.
If it's a HTML application (e.g. Windows HTA, Electron app, Chrome desktop app, etc) then that's another topic.

Problems with Color class (System.Drawing) in UWP on Raspberry Pi

I struggle to implement some basic operations with Color class on my Raspberry Pi running Windows 10 IoT. After I instantiate a Color object by rgb data
basic methods like GetBrightness() or GetSaturation() lead to a SEHException.
Thrown exception: System.Runtime.InteropServices.SEHException (0x80004005): External component has thrown an exception.
Typing the operation in the "immediate window" in Visual Studio during debugging yields the desired result though. I don't even know where to start to locate the actual issue.
I'm using a Raspberry Pi 2b with Windows 10 IoT Core 17763 (also project build setting), and trying to run an C# UWP-Project on it.
I tried several target versions and also updated my machine. Didn't help so far.
// using System.Drawing;
Color color1 = Color.FromArgb(x, y, z);
float brt = color1.GetBrightness(); // <= Not passing this line
float sat = color1.GetSaturation();
Like mentioned, the results in immediate window seem plausible and works at least. Why this isn't also running in code. Where is the code actually processed, that is typed in the immediate window?
System.Drawing is not possible in Windows Universal app, it is the .NET namespace for working with GDI+.
You can make use of SharpDX which provides wrappers for Direct2D, DirectWrite, and the Windows Imaging Component (WIC). The GetHue method is included in ColorBGRA.cs.

How to detect GDI resource leaks in managed C# screensaver?

Here's my problem ... I suspect a GDI Resource leak in my C# screensaver that uses only managed code. Error: 'Out of memory' after many operations. I compile using VS Prof 2013 Update 4 and run under Windows 7 64bit. I use Dispose and non-static routines wherever possible. Here are my issues:
Being a screensaver, I have not even been able to use the JITdebugger
(the application load process just hangs)
Deleaker is a tool for C++, not C#
Detailed internet links apply to Windows 9x / Windows 2000 (MSDN Magazine from 2001) or Windows 2000 / Windows XP (also MSDN Magazine)
can't download GDIObj (apparently unavailable)
I can display 'GDO Objects' in Task Manager but the screensaver uses the whole screen and overlays it while running
... also with GDIview from NirSoft (Explorer.exe strangely has the highest count of GDI objects)
Thus my questions are ...
do developers no longer have GDI resource leaks using Visual Studio C#?
can GDI+ be used to continually update the screen? (in a simulation app)
do developers no longer use GDI/GDI+ for 2.5D? (= multi-layer 2D)
if so, what technology is best suited for a simulation-type application that
runs forever (in theory)
regularly updates parts within the whole screen (text & graphics)
runs in real-time (100 msec difference is tolerable but it must keep pace with a radio clock).
high resolution graphics (to the pixel in 1920x1080 format), i.e. no low-res gaming use of DirectX; no use of single-precision GPU arithmetic
C# almost worked!
In appreciation of your creative responses...
UPDATE 1
I implemented GetGuiResources() in C# as follows (code extract):
using System.Diagnostics;
using System.Runtime.InteropServices;
static class FreeMem
{
[DllImport("user32.dll")]
static extern uint GetGuiResources(IntPtr hProcess, uint uiFlags);
public static int GetGuiResourcesGDICount()
{
return (int)GetGuiResources(Process.GetCurrentProcess().Handle, 0);
}
public static int GetGuiResourcesUserCount()
{
return (int)GetGuiResources(Process.GetCurrentProcess().Handle, 1);
}
}
and my application showed
a stable GCIcount between 38 and 42
a stable UserCount between 18 and 19
until the intentionally (user-) provoked crash after which it showed
GCIcount = 62
UserCount = 35
i.e. nothing dramatic.
Please note that I regularly execute the following on a 1920 x 1080 pixel bitmap:
Graphics grTemp = Graphics.FromImage(HighlightedTZ.p_bmpC);
grTemp.DrawImage(DayNight.p_bmp, new Rectangle(0, 0, DayNight.p_bmp.Width, DayNight.p_bmp.Height));
grTemp.Dispose();
You can use a second system to remotely debug your C# code.
If you only have one machine available, you can create a second system using a virtual machine system, such as Oracle's free Virtual Box (I recommend this), or some other VM software. You will need a valid Windows license, because even though your VM software is emulating a computer, the new OS will count it as a real computer. If you have an MSDN subscription, then you can get extra OS license keys for debugging and development purposes.
Put your product on that VM, install the Visual Studio remote bugger on the VM, start it up and make sure you can access it from your host machine's Visual Studio (by using attach to process from your host machine's Visual Studio). Now you are ready to remotely debug.
Let your screen saver start on the VM. Once it starts, start up your host VS debugging by attaching to the screen saver using the remote debugger. Now set your breakpoints and watchpoints and debug as normal.
If you have a second windows box available, then you don't need the Virtual Machine software. Just install your product (screen saver) on the second windows machine, install the Visual Studio remote debugging toolset on it, start remote debugger, set it to allow you to access it, start up your preferred machine's Visual Studio, wait for the screen saver to start on second machine, attach from your Visual Studio, set break points, watch items, and debug as normal.

XNA 4.0 game doesn't do anything when ran on another PC

This issue is getting real tiresome and I've been spending atleast 2 days looking around for an answer. Basically, I want to publish a game, and I've hired a friend of mine to test it out before I officially release it. Whenever he runs it, reports as "nothing happends".
These conditions are met:
He has installed the .NET Framework 4.0 and the XNA Redistributable 4.0 (he most likely also has installed other .NET Frameworks and XNA Frameworks as well, because nothing worked).
The game is compiled onto a Release build.
GamerService referenced is removed.
A possible issue could be that he's using Win8, but as my searching experience goes, XNA DEVELOPMENT is only restricted on Windows 8, right?
So, what's going on? I'm clueless.. I even put a MessageBox.Show(); after the execution of my game in my Program.cs file via try/catch, and no results.
Are there any extreme conditions in my code that I need to meet?
Any site describing 100% of all requirements to run an XNA game and the most proper way to build it?
Any issues when using non-distributable "developer tools" in XNA coding? If so, what includes in these "developer tools", and what do I need to modify? (I noticed that on another thread).
An answer to this issue would more than make my day...
Ah, and also, I tried running it on a virtual machine ( Windows 7 ) but then it spat out a messagebox saying Index outside the bounds of the array on a perfectly valid code execution, and various other random errors such as missing files when they clearly are there.
Thank you greatly!
In summary I think your app wont run on Windows 8, let me explain:
Windows 8
A possible issue could be that he's using Win8, but as my searching experience goes, XNA DEVELOPMENT is only restricted on Windows 8, right?
Officially, desktop games using unmodified Microsoft XNA 4/is not supported on Windows 8 in any form:
Microsoft officials have said the XNA tools/runtime environment used primarily by game developers isn't supported on Windows 8. - Read more...
Redistributables
Any issues when using non-distributable "developer tools" in XNA coding?
That depends on whether they are required at runtime on the target machine. That might sound like an oxymoron but in Windows c/c++, I can have an app that depends on Microsoft DLLs but we are not allowed to deploy the DLLs, one must depend on it being present in the OS; service pack or some other form. Is there something you are missing?
Windows 7
Ah, and also, I tried running it on a virtual machine ( Windows 7 ) but then it spat out a messagebox saying Index outside the bounds of the array on a perfectly valid code execution
This is more interesting and I suspect is one of the more testable aspects of your application (also that it is not Windows 8). I suggest you setup a remote-debug session to your Win7 VM or if that is not possible, use Debug.WriteLine() or equivalent displaying critical state contents.

Is it possible to write a Ping class in C# that will run within Windows 8 Metro environment?

Since the Metro environment on Windows 8 lacks most of the .NET framework class libraries or contains a substancially pared down version, is it possible to execute a "ping" from a Metro style application? There is support for Sockets, so I guess there is hope, but I don't know where to start, since every "C# Ping" example uses System.Net.NetworkInformation.Ping and that is not available in WinRT.
I also looked into the source code for Mono, and their ping implementation fires up ping.exe and returns the result from the standard output window of the command line.
No, unfortunately not. ICMP is not supported in WinRT: IcmpCreateFile and related Win32 APIs are only available in the "desktop" API partition. ICMP can be implemented using raw sockets but since these are not supported in WinRT (and usually require elevation, anyway), this option is also not available to you.
As the developer of a Windows Store network scanning tool myself (http://lanscan.rcook.org/), I'd love to be able to do this.

Categories

Resources