Print data from VB.net into c# windows form - c#

I have application made from 2 solutions. One made in Visual Basics other in C# which is console-application.
I'm trying to remake that program into windows form application, however, all output is made using Console.WriteLine() commands. Output from C# I could quite easily get with richTextBox.AppendText().
When trying to output from Visual basic part, I can't do that, as I understand it's due to that fact that it is reference. What I could do to solve this?

You can do it in the VisualBasic part like this (it shows it in C# but it's quite similar in VisualBasic): take a StringBuilder and add all your old statements there and then put it in the TextBox as once:
//// Your old code:
//Console.WriteLine("xyz1");
//// Do anything...
//Console.WriteLine("xyz2");
//// Do anything...
//Console.WriteLine("xyz3");
//// Your new code:
StringBuilder sb = new StringBuilder();
sb.AppendLine("xyz1");
//// Do anything...
sb.AppendLine("xyz2");
//// Do anything...
sb.AppendLine("xyz3");
this.textbox1.Multiline = true;
this.textbox1.Text = sb.ToString();
=> This code will work, if you will need only the results of the Console.WriteLine() Messages: if you need the Messages immediately, you will probably need a splash screen, like this: Making a splash screen, or How to build splash screen in windows forms application? or a ProgressBar maybe could help you: How to use WinForms progress bar?

Related

UIAutomation throws AccessViolationException on Windows 11

The issue:
We have an application written in C# that uses UIAutomation to get the current text (either selected or the word behind the carret) in other applications (Word, OpenOffice, Notepad, etc.).
All is working great on Windows 10, even up to 21H2, last update check done today.
But we had several clients informing us that the application is closing abruptly on Windows 11.
After some debugging I've seen some System.AccessViolationException thrown when trying to use the TextPatternRange.GetText() method:
System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'
What we've tried so far:
Setting uiaccess=true in manifest and signing the app : as mentionned here https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/350ceab8-436b-4ef1-8512-3fee4b470c0a/problem-with-manifest-and-uiaccess-set-to-true?forum=windowsgeneraldevelopmentissues => no changes (app is in C:\Program Files\
In addition to the above, I did try to set the level to "requireAdministrator" in the manifest, no changes either
As I've seen that it may come from a bug in Windows 11 (https://forum.emclient.com/t/emclient-9-0-1317-0-up-to-9-0-1361-0-password-correction-crashes-the-app/79904), I tried to install the 22H2 Preview release, still no changes.
Reproductible example
In order to be able to isolate the issue (and check it was not something else in our app that was causing the exception) I quickly made the following test (based on : How to get selected text of currently focused window? validated answer)
private void btnRefresh_Click(object sender, RoutedEventArgs e)
{
var p = Process.GetProcessesByName("notepad").FirstOrDefault();
var root = AutomationElement.FromHandle(p.MainWindowHandle);
var documentControl = new
PropertyCondition(AutomationElement.ControlTypeProperty,
ControlType.Document);
var textPatternAvailable = new PropertyCondition(AutomationElement.IsTextPatternAvailableProperty, true);
var findControl = new AndCondition(documentControl, textPatternAvailable);
var targetDocument = root.FindFirst(TreeScope.Descendants, findControl);
var textPattern = targetDocument.GetCurrentPattern(TextPattern.Pattern) as TextPattern;
string text = "";
foreach (var selection in textPattern.GetSelection())
{
text += selection.GetText(255);
Console.WriteLine($"Selection: \"{selection.GetText(255)}\"");
}
lblFocusedProcess.Content = p.ProcessName;
lblSelectedText.Content = text;
}
When pressing a button, this method is called and the results displayed in labels.
The method uses UIAutomation to get the notepad process and extract the selected text.
This works well in Windows 10 with latest update, crashes immediately on Windows 11 with the AccessViolationException.
On Windows 10 it works even without the uiaccess=true setting in the manifest.
Questions/Next steps
Do anyone know/has a clue about what can cause this?
Is Windows 11 way more regarding towards UIAutomation?
On my side I'll probably open an issue by Microsoft.
And one track we might follow is getting an EV and sign the app itself and the installer as it'll also enhance the installation process, removing the big red warnings. But as this is an app distributed for free we had not done it as it was working without it.
I'll also continue testing with the reproductible code and update this question should anything new appear.
I posted the same question on MSDN forums and got this answer:
https://learn.microsoft.com/en-us/answers/questions/915789/uiautomation-throws-accessviolationexception-on-wi.html
Using IUIautomation instead of System.Windows.Automation works on Windows 11.
So I'm marking this as solved but if anyone has another idea or knows what happens you're welcome to comment!

How to use GetExtentOfWord in the new IAsyncQuickInfoSource API?

I am writing a C# extension for Visual Studio and I am trying to use the new API for QuickInfos: https://github.com/Microsoft/vs-editor-api/wiki/Modern-Quick-Info-API. I am prototyping based on this sample: https://github.com/microsoft/VSSDK-Extensibility-Samples/tree/master/AsyncQuickInfo. It works fine as long as I don't change it.
The sample is only focusing on the whole line:
var line = triggerPoint.Value.GetContainingLine();
However, I need to get the hovered word. In the old API, I was using this and it was working fine:
var navigator = provider.NavigatorService.GetTextStructureNavigator(buffer);
var hoveredWord = navigator.GetExtentOfWord(triggerPoint.Value);
Unfortunately, Visual Studio will freeze as soon as I call GetExtentOfWord with the new API!!! More precisely, I will pass a few times and then it will freeze (quite shortly).
What should do I to be allowed to get the hovered word extent with the new IAsyncQuickInfoSource API?
Thanks!

Selenium doesn't recognize new opened window -Selenium C#

Seems like I'm facing some sync issues in my code.
during my process, I'm clicking a button which opens a new window.
I'm swicthing to the new window by the following code.
_webdriver.SwitchTo().Window(_webdriver.WindowHandles.Last();
Then, I'm inserting data into fields within the next window.
problem is that sometimes the objects in the "next window" are not being found.
I'm getting : "can't find element" error.
for me it seems like a sync problem , meaning , DOM issues.
so I have tried using :
_webdriver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
and I even tried :
Thread.Sleep(3000);
Unfortunately , seems like most of the times the problem is that selenium didn't switch to the new window(could see it when debugging).
I'll be happy to have your assistance.
You could wait for two windows and then set the context to the new one:
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
// wait for 2 windows
ReadOnlyCollection<String> handles = null;
wait.Until((d) => (handles = driver.WindowHandles).Count > 1);
// set the context on the new window
driver.SwitchTo().Window(handles[handles.IndexOf(driver.CurrentWindowHandle) ^ 1]);
i am not sure how this is done in C# but i think selenium is same you just have to use C# syntax for loop.
//Switch to newly opened window (JAVA)
for(String winHandle : driver.getWindowHandles()){
driver.switchTo().window(winHandle);
}
this is how i do in Java. you will get driver.getWindowHandles() same method in C# as well, if i am not wrong as this is selenium method.
hope this is helpful to you.

Running Matlab GUI from C#

In my project, I am integrating Matlab GUI application with in a C# application.
The solution I thought about is to create a standalone application from the Matlab GUI and start it via a button in C#:
Process exeProcess = Process.Start("Data_Capture_Direct_call.exe");
if(!exeProcess.HasExited)
{
exeProcess.WaitForExit();
}
exeProcess.Close();
The problem is that after the splash screen of Matlab GUI is closed and before the actual program opens, C# detects that the program has been closed already and carries on to the next line.
In addition, the next few lines of code are not properly executed:
List<String> Movement = new List<String>();
List<String> Repetition = new List<String>();
List<String> Duration = new List<String>();
using (CsvFileReader reader = new CsvFileReader("capture.csv"))
{
CsvRow row = new CsvRow();
while (reader.ReadRow(row))
{
Movement.Add(row[0]);
Repetition.Add(row[1]);
Duration.Add(row[2]);
}
}
for (int i = 1; i < Movement.Count; i++)
{
dataGridView1.Rows.Add(i, Movement[i], Repetition[i], Duration[i]);
}
What happens is that after the C# wrongly detects closure of the process, the capture.csv file becomes empty and data is not loaded into the data grid.
Please let me know where I am making a mistake or if there is a better way to do this!
In my solution you should do some settings before starting code in order to use Matlab instance in a C# application.
Adding neccessary dll :
First we will add dll reference with COM interface. Click RMB on project and choose [Add Reference] option. In new window click COM tab. In search text box write 'Matlab'. Then choose "Matlab Application (Version 7.10) Type Library".
You should get references like below :
Now you can easily do whatever you can do on Matlab in C# . Lets give an basic example :
var acCtx = Type.GetTypeFromProgID("matlab.application.single");
var matlab = (MLApp.MLApp)Activator.CreateInstance(acCtx);
these two lines are creating of matlab instance in code.Now let's make a easy computation on Matlab.
Console.WriteLine(matlab.Execute("1+2")); // This will output 3 on console.
matlab.Quit(); // you should close matlab in order to clean memory
Lets give solution to your actual problem.You want to execute a Matlab GUI program.And I think your Gui is recording some data to CSV file.Then your C# program processes that data.You should note that you can call your GUI in Matlab just writing your name of program as command.Suppose that you have a GUI called myGui.m.You can call that gui by calling myGui in command line as you can write 1+2 to get 3.
Let's call gui.
matlab.Execute("myGui"); // This will execute your Gui. You can use buttons to save data to CSV file
matlab.Quit();
I have extended example on this page :
Source

How can I change the Paperspace background using .NET in AutoCAD

I've asked this question over in the Autodesk Forums, and no one seems to have any answer. I'm hoping someone here might.
I'm simply trying to programatically change the Paperspace(Layout Tab) background color. Also the Command Prompt Text("Command:" to "User decides").
This is being coded to run for Autocad and Bricscad. The Bricscad system variables are:
BKGCOLORPS
CMDLNTEXT
I think the background color is located in:
...DocumentManager.MdiActiveDocument.Editor.Document.GraphicsManager but I'm still not figuring out how to get/set it.
The Command Prompt Text, I don't even know where to start.
Edit: got somewhere. Here's the layout background anyways. Still waiting on a support request for the command line prompt.
Had to add the Autodesk.AutoCAD.Interop.dll reference on top of the 3 standard ones(accoremgd/acdbmgd/acmgd).
AcP.AcadPreferences acBkgColor = (AcP.AcadPreferences)AcAp.Application.Preferences;
if (acBkgColor.Display.GraphicsWinLayoutBackgrndColor == 0) { cbxPsBackground.Checked = true; }

Categories