I have made a small c# winforms program which among other stuff, prints barcodes. On some client machines where it operates, some other software for printing barcodes overrides my settings for printing the barcode and it resizes just the barcode.
If I change the code just for that machine, it either repositions the image (makes it smaller as well), or stretches it so wide that it cuts off one third of it. Currently I am only using the printing settings to set the margins to 0 and set the paper mode to landscape in the print dialog, and the image size is fixed in the printing process(I used constants). Below is the code for when the user clicks the print button, and also two constants defined outside of it.
const int barcodeX = 570;
const int barcodeY = 135;
private void Print_Click(object sender, EventArgs e)
{
DocPrint.DocumentName = "Document";
elements = 0;
PrintDialog.Document = DocumentDrucker;
DocPrint.DefaultPageSettings.Landscape = true;
DocPrint.DefaultPageSettings.Margins.Top = 0;
DocPrint.DefaultPageSettings.Margins.Left = 0;
DocPrint.DefaultPageSettings.Margins.Right = 0;
DocPrint.DefaultPageSettings.Margins.Bottom = 0;
//DocumentDrucker.OriginAtMargins = false;
if (PrintDialog.ShowDialog() == DialogResult.OK)
DocPrint.Print();
}
Also the lines to encode and print the barcode in the printing process. The barcodePoint is where the barcode is positioned, on the paper.
b.Encode(TYPE.CODE128A, "SBD" + currentItem.Text.Substring(0, 3) + currentItem.Text.Substring(4), Color.Black, Color.Transparent, barcodeX, barcodeY);
graphic.DrawImage(b.EncodedImage, barcodePoint);
The program runs fine under any other circumstances, so I have identified the problem, I just do not know how to go around the other software's settings. I have already reinstalled the drivers for the printer (no success), as well logged in as a different user on the same computer, and that made my program work. So it has something to do with the software installed on it, I just don't know what.
At first I thought it was a problem with the drivers and the OS, but I tried it on other computers and it worked fine as well. The problem persists just on the computers with the software.
Is there any way to make my program force it's printing settings for the barcode image, since the software installed on the machines always uses it's own settings? Or to make sure that the settings in my code will not be changed?
Uninstalling the software is not an option, as it is used for other processes.
EDIT: I have run the program from both my user logon (no software) and the target machine user (both on the same machine). The settings were identical in both cases, the only thing different was that on the target machine, the software was installed. What are some ways to make sure that my settings are enforced, instead of an X program overwriting them?
Related
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!
I have a service which prints. Up until now the service has been printing using the WPF System.Windows.Controls.PrintDialog.PrintDocument method however due to various issues (performance, windows update bugs, 32 bit service on 64bit system issues etc) I am converting to use the traditional System.Drawing.Printing.PrintDocument method.
As this is running as a service I want this to always print using the default printer preferences (which include things like media settings and print speed for industrial label printer such as the Intermec/Honewell PM43)
Previously I had done this using PrintDialog.PrintTicket = PrintQueue.DefaultPrintTicket.Clone
However I cannot find the equivalent method in System.Drawing.Printing.PrintDocument and the service is not picking up the default printer preferences as set in the printer properties (specifically Print Speed in this case)
So what is the equivalent of PrintDialog.PrintTicket = PrintQueue.DefaultPrintTicket.Clone in System.Drawing.Printing.PrintDocument?
The following question helped me find an answer
Can't change DEVMODE of a printer
//Get the registry key containing the printer settings
var regKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("System\\CurrentControlSet\\Control\\Print\\Printers\\" + PrinterName);
if (regKey != null)
{
//Get the value of the default printer preferences
var defaultDevMode = (byte[])regKey.GetValue("Default DevMode");
//Create a handle and populate
var pDevMode = Marshal.AllocHGlobal(defaultDevMode.Length);
Marshal.Copy(defaultDevMode, 0, pDevMode, defaultDevMode.Length);
//Set the printer preferences
pd.PrinterSettings.SetHdevmode(pDevMode);
//Clean up
Marshal.FreeHGlobal(pDevMode);
}
I have writen some simple C# Tool that Prints PDFs with the Help of SpirePDF
In the Tool i can select The Printer and its PaperTray
I have 2 Printers here and they are working fine with my code (The correct tray is used)
On an other machine with other Printers, it doesnt work, the correct Printer is choosen, but the PaperTray is alway the same (Manual Feed), no matter which Tray i choose.
printDocument.PrinterSettings.PrinterName = PrinterSettings.InstalledPrinters[MyPrinterConfiguration.GetPrinterIndex(#"invoice_print")];
printDocument.DefaultPageSettings.PaperSource = printDocument.PrinterSettings.PaperSources[MyPrinterConfiguration.GetPrinterTrayIndex(#"invoice_print")];
MyPrinterConfiguration is an Dictionary that hold the indexes of the Trays and Printer on the System.
Are there any other methods to set the PaperSource for this Document?
My Printers are from Samsung and Brother
the others from HP and Brother (both are not working) so it seem not to be a driver Problem.
I have found a solution:
Setting the PaperSource in self-created PrinterSettings seems not to work for some Printers, but when i make a Printdialog, let the User choose the Settings (PaperSource, PaperType and so on) and take theese settings (unchanged) to apply them on the PrintDocument, then it works for all my testet printers.
I think PrinterSettings from PrintDialog have other or more characteristics than i can set programaticly.
if (printDialog.ShowDialog() == DialogResult.OK) {
gpsMyPrintSettings.SetSettingsForType( "badge", (PrinterSettings) printDialog.PrinterSettings.Clone() );
}
printDocument.PrinterSettings = gpsMyPrintSettings.GetSettingsForDocumentType( "badge" );
printDocument.Print();
I'm working on a portion of an application that has a 'finder' tool that allows the user to drag and drop a finder onto an application or internet explorer web browser so that our program can locate it and do what it needs to do. This portion of the application was not under any active development for the last few years (last time I believe IE 7 was the latest browser), but it has worked for IE 9 and below. Starting at IE 10 we get problems, and I specifically am using IE 11.
The following code locates the different Internet explorer windows (including tabs) and file explorer windows. We made a quick VB script for extra testing -
dim objShell
dim objShellWindows
set objShell = CreateObject("shell.application")
set objShellWindows = objShell.Windows
if (not objShellWindows is nothing) then
WScript.Echo objShellWindows.Count
for each win in objShellWindows
wscript.Echo TypeName(win)
WScript.Echo win.LocationUrl
WScript.Echo win.LocationName
WScript.Echo win.HWND
next
end if
set objShellWindows = nothing
set objShell = nothing
The above code will execute without error, and it gives the URL and title bar name of all the tabs we have open.
Below is our C# code. It attempts to get the main IE window (not the tab). this.Handle is the handle of this main IE window that the finder tool gets when the user drops it. We're attempting to iterate through the open windows and find the Internet Explorer window that the user selected. This particular snippet is changed slightly from our original implementation, but the end result is the same. As soon as it hits test = window.Item(i) it throws a UnauthorizedAccessException.
ShellWindows windows = null;
IWebBrowser2 shellWindow = null;
IHTMLDocument2 actualDoc = null;
Type shellApplicationType = Type.GetTypeFromProgID("Shell.Application");
Shell32.Shell shellInterface = (Shell32.Shell)Activator.CreateInstance(shellApplicationType);
windows = (ShellWindows)shellInterface.Windows();
bool found = false;
for (int i = 0; i < windows.Count; i++)
{
try
{
object test;
try
{
test = windows.Item(i); //Exception here
shellWindow = (IWebBrowser2)test;
}
catch
{
}
if (shellWindow != null && (IntPtr)shellWindow.HWND == this.Handle)
{
//the rest of the code gets the correct tab from the main IE window
This is the original unedited code from when we first revisited this portion of the program.
ShellWindows windows = null;
IWebBrowser2 shellWindow =null;
IHTMLDocument2 actualDoc = null;
windows = new SHDocVw.ShellWindowsClass();
bool found = false;
for (int i = 0; i < windows.Count; i++)
{
try{
shellWindow = windows.Item(i) as SHDocVw.IWebBrowser2; //Exception here
if (shellWindow != null && (IntPtr)shellWindow.HWND == this.Handle)
{
I would also like to note that instead of a for loop I have tried a foreach loop that followed this syntax
foreach(IWebBrowser2 browser in windows)
and
foreach(InternetExplorer browser in windows)
In those instances, the loop skips over the IE window.
I have looked at IE's security settings. I have disabled Enhanced Protection Mode and allowed cross domain. There does not seem to be a lot of information on this issue, and every approach we try seems to always end up with an UnauthorizedAccessException.
Edit: In response to Hans answer, I do not have any anti malware running on this machine. It is a virtual machine with windows 7 that has the latest SP and updates (no microsoft security essentials). I tried running the app on a 32 bit machine with similar settings and it also failed. After testing it on IE 11, I uninstalled IE 11, rebooted, tried IE 10 (it failed, same error), uninstalled IE 10, rebooted, tried IE 9, and it worked without making any other changes to the system.
Here is the SSCCE as requested by Hans. This code actually works on my target machine. I will return to this post in the next day or two while I handle other tasks that require my attention.
I build this as a 32 bit console app, and ran it on a 64bit machine.
using System;
using SHDocVw;
using mshtml;
namespace GetBrowserSSCCE
{
class Program
{
static void Main(string[] args)
{
ShellWindows windows = null;
IWebBrowser2 shellWindow = null;
windows = new SHDocVw.ShellWindowsClass();
for (int i = 0; i < windows.Count; i++)
{
try
{
shellWindow = windows.Item(i) as SHDocVw.IWebBrowser2;
Console.WriteLine(string.Format("Window Found. HWND: {0}\nName: {1}", shellWindow.HWND, shellWindow.Name));
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine("UnauthorizedAccessException caught. Exception Text: " +ex.Message);
}
}
Console.ReadLine();
}
}
}
That this fails in your C# program but not when you run it from the VBScript interpreter points strongly to an environmental problem. Both use the exact same shell interface. The specific exception (underlying error code is 0x8007005) has been reported before on the interwebs but never diagnosed.
First thing you should focus on whenever you have an environmental problem, particularly the kind associated with access rights, is the anti-malware installed on the machine. Disable it and try again.
Second one you should focus on is a quirk associated with ShellWindows, it doesn't just enumerate Internet Explorer windows but also Windows Explorer windows. You've been looking at having sufficient access to IE but that isn't enough, this code can also fail if you happen to have an Explorer window opened and there's an access problem with the explorer.exe process. Do note that your Activator.CreateInstance() method call is not equivalent to the VBScript code, Activator.GetObject() is. So your changes would actually make the problem worse if this is underlying problem.
Third detail that's worth checking is the bitness of your process. By default, your VBScript code will run in the 64-bit script interpreter on a machine that boots the 64-bit version of Windows. But the default setting for a C# project is to run in 32-bit mode. Right-click your EXE project, Properties, Build tab and tinker with the Platform target setting, the 'Prefer 32-bit' checkbox if you see it. This is not an explanation for the error code, it can however affect the effectiveness of anti-malware to intrude.
first of all, I have been learning Microsoft Surface for about 1-2 months now and my project requires me to look into incorporating the use of a VNC viewer into my Surface Application.
I have looked into VNCSharp and VNCSharpWpf from VNC control for WPF application and I'm currently using VNCSharpWpf as it has better user interaction in the WPF environment although the performance is somewhat lacking compared to the viewers out there.
Here is my question, is there any difference between Microsoft Surface WPF and the default WPF in how they handle framebuffer/threads ?
I noticed that when the client attempts to draw the rectangle in the Surface environment, it will cause an exception where by the rectangle to be updated has 0 width and height.
However, when I test it on the sample code the author of VNCSharpWPF provides (WPF on Window ), the error never occur.
I tried to workaround by setting and if clause to only draw if the width and height of the rectangle decoded is not 0. Although it prevents the application from crashing, it will results in dead pixel around the screen whenever there are changes in the screen in the server-end.
I've been stuck with this situation for 1-2 weeks already and have ran out of ideas and is in need of some guidance on where I should look into
Or is there is any cool VNC viewer/server out there that I can use for my Surface project that I've missed out ?
I've been having the same issue with VNCSharp WPF on a PC, and when tested VNC Sharp for WinForms, then it worked OK.
Furthermore, When I've tested VNCSharp for WPF on Debug, then it works OK, but failed on Release.
I've wasted several hours debugging it (I've learned some parts of the VNC protocol for that matter, since I've found out that it somehow reads the width and the height of the remote device from the wrong location in the netowrk stream).
The bug is related to floats comparison. It depends on the machine you have (it might work well on some machines and on others it might not)
Please look at VncClient, Line 349:
if (rfb.ServerVersion == 3.8) rfb.ReadSecurityFailureReason();
If you, while debugging, put a breakpoint there, you will see that rfb.ServerVersion is 3.8f
ServerVersion returns a calcualted float:
public float ServerVersion {
get {
return (float) verMajor + (verMinor * 0.1f);
}
}
You should expect that since ServerVersion is 3.8, then it will execute
ReadSecurityFailureReason which reads some extra bytes that are needed for the code to work, but on Release (Ctrl+F5, since in Visual Studio Release, while the code is being debugged, it will probably work OK) those extra bytes will not be read, so the width and height will be read from the wrong location on the stream, causing it to be 0px over 0px
For demontrating my point, please take the following code, and compile it as x86 (I'm assuming that you have an x64 machine and an x64 OS, since this is the situation here):
class Program
{
static void Main(string[] args)
{
SomeVersion someVersion = new SomeVersion(3, 8);
if (someVersion.Version == 3.8f)
{
Console.WriteLine("Version is 3.8");
}
Console.ReadLine();
}
}
public class SomeVersion
{
private int _major;
private int _minor;
public SomeVersion(int major, int minor)
{
_major = major;
_minor = minor;
}
public float Version
{
get
{
return (float)_major + (_minor * 0.1f);
}
}
}
Run the code in Debug x86 (both with visual studio debugger and with Ctrl+F5)
You should see that you get the message: "Version is 3.8" on both cases.
Now change it to Release x86... Run it with F5. You should get the message.
Now run it with Ctrl + F5... WTF??, no message!
In order to fix the bug in the Vnc Sharp WPF, I've took the class RfcProtocol, and added another function:
public bool CompareVersion(int major, int minor)
{
return major == verMajor && minor == verMinor;
}
Now on VNC Client (both line 188 and 349), I've changed the code so it will compare using the new function, instead of comparing 2 floats.