How to programmatically open control panel? - winapi

How do I open a custom control panel programmatically, like custom.cpl? Specifically, how do I open a 64-bit cpl when running as 32-bit application?

Vista added support for canonical names so you don't have to hard code dll filenames and tab indexs
Example:
WinExec("%systemroot%\system32\control.exe /name Microsoft.WindowsUpdate", SW_NORMAL);
(Names are always in english)
See MSDN for a list
XP/2000 supports "control.exe mouse" and a few other keywords, see the same MSDN page for a list (You can probably find some undocumented ones by running strings on control.exe)

Since I didn't find a good answer here on SO, here's the solution of my research:
Start a new application "control" that gets the name of the control panel as its first parameter:
::ShellExecute(m_hWnd, NULL, _T("control.exe"), _T("access.cpl"), NULL, SW_SHOW);

just use this....
ProcessStartInfo startInfo = new ProcessStartInfo("appwiz.cpl");
startInfo.UseShellExecute = true;
Process.Start(startInfo);

Step1 :
Read System Directory from the machine.
Step2 :
Use Process to start ControlPanel
**Process.Start(System.Environment.SystemDirectory + #"\appwiz.cpl");**

As i previously mentioned in another Question:
If you type "Start Control" or "Control" into Command Prompt it will open Control Panel.
Therefore just run a Process.
This Code (Bellow) worked perfectly for me:
public Form1()
{
InitializeComponent();
}
#region Variables
Process p;
#endregion Variables
[...]
void myMethod()
{
try
{
p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.Start();
p.StandardInput.WriteLine("start control");
p.StandardInput.Flush();
p.StandardInput.Close();
Console.WriteLine(p.StandardOutput.ReadToEnd());
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}

Related

Best way to determine if simple or extended MAPI was loaded

How can I simply determine if simple or extended MAPI is loaded.
Because I want to diable my add in wenn simple MAPI is loaded.
I'm working with Add-In Express and Redemption.dll.
Using the Windows "Send To" command actually integrates with SendMail.dll. AFAIK you can't intercept these calls to do something custom, but you can add your own shortcuts in the context menu:
http://www.slipstick.com/outlook/create-a-custom-send-to-shortcut/
What about this solution? Could this leading to problems?
Outlook.Application outlookApp = null;
Outlook.Explorer outExp = null;
try
{
outlookApp = (Outlook.Application)AddinModule.CurrentInstance.OutlookApp;
outExp = outlookApp.ActiveExplorer() as Outlook.Explorer;
if (outExp != null)
{
// extended stuff
} else {
// simple stuff
}
}

Telerik Winforms Reports freeze on Terminal Services

I am using Telerik reports in our app and it is being accessed mostly through an RDP session running in "app mode". Everything works fine locally but when I put it on the TS machine it freezes after the print dialog comes up.
The standard print dialog comes up and you can choose the printer and hit ok but then a small box opens with header of Printing... and then never does anything.
I am not sure what code to post since its fine locally, let me know what you want to see. also printing other things like the Telerik grids and charts are fine.
Found the answer on my own.
I created a standard printdialog screen and "rolled my own" print method and all seems to be good. Hope this helps someone else.
private void reportViewer1_Print(object sender, CancelEventArgs e)
{
this.Cursor = Cursors.WaitCursor;
e.Cancel = true;
try
{
PrintDialog pd = new PrintDialog();
pd.PrinterSettings = new System.Drawing.Printing.PrinterSettings();
var result = pd.ShowDialog();
if (result ==DialogResult.OK)
{
// Print the report using the custom print controller
var reportProcessor
= new Telerik.Reporting.Processing.ReportProcessor();
reportProcessor.PrintReport(this.reportViewer1.ReportSource, pd.PrinterSettings);
}
}
catch (Exception ex)
{
Program.ExceptionHandler(ex);
}
this.Cursor = Cursors.Default;
}

Setting Date and Time on Windows Embedded Standard 7 OS

I am working on setting Date and Time on Windows Embedded Standard 7 OS using C# .net.
I tried changing the system date using code in following link.
http://www.pinvoke.net/default.aspx/kernel32.setsystemtime
But I also saw that one should get the privileges to change the same. But I am receiving an error. here is the code to
Privileges.EnablePrivilege(SecurityEntity.SE_SYSTEMTIME_NAME);
if (SetSystemTime(ref st) == 0)
{
return 0;
}
return 1;
For getting the privaleges I used the code from the following link.
http://www.pinvoke.net/default.aspx/advapi32/AdjustTokenPrivileges.html
C# Sample Code 2 (With full error handling):
I have question:
Is it possible to change the Date and Time using PInvoke. If it is possible what are the change/Setting I should do at the OS.
And what are the other ways to change the date and time.
thank you
Edit:
[DllImport("kernel32.dll")]
extern static uint SetSystemTime(ref SYSTEMTIME lpSystemTime);
public int SetSystemDateTime(DateTime NewSystemDateTime)
{
SYSTEMTIME st = new SYSTEMTIME();
st.wYear = (ushort)NewSystemDateTime.Year;
st.wMonth = (ushort)NewSystemDateTime.Month;
st.wDay = (ushort)NewSystemDateTime.Day;
st.wHour = (ushort)NewSystemDateTime.Hour;
st.wMinute = (ushort)NewSystemDateTime.Minute;
st.wMilliseconds = (ushort)NewSystemDateTime.Millisecond;
Privileges.EnablePrivilege(SecurityEntity.SE_SYSTEMTIME_NAME);
if (SetSystemTime(ref st) == 0)
{
return 0;
}
return 1;
}
Ok I did some research and I tried few things. You need admin permissions to change system date and time, one solution is to add
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
to application manifest file, this way the application will always ask user for permissions.
On code project there is an article that maybe able to help ypu without adding manifest file.
http://www.codeproject.com/Articles/125810/A-complete-Impersonation-Demo-in-C-NET
I finally found the solution. Code in the following link works fine for me:
http://www.pinvoke.net/default.aspx/kernel32/SetLocalTime.html
Also following code I found in one of the posts in stackoverflow, helped me.
using System.Security.Principal;
bool IsUserAdministrator()
{
bool isAdmin;
try
{
WindowsIdentity user = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(user);
isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
}
catch (UnauthorizedAccessException ex)
{
isAdmin = false;
}
catch (Exception ex)
{
isAdmin = false;
}
return isAdmin;
}

How to clear browser cache automatically in Selenium WebDriver?

How to clear browser cache before every test run? I tried with driver.manage().deleteAllCookies(); in setUp method after creating the driver instance, it is working for firefox, but for IE no use. Is there any solution for IE please provide me..
There is a driver capability you can set as follows:
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);
It worked for me on IE11.
Source:
http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/ie/InternetExplorerDriver.html
Use the below code to clear cache in IE
try {
Runtime.getRuntime().exec("RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255");
} catch (IOException e) {
e.printStackTrace();
}
Using this post, How To: Execute command line in C#, get STD OUT results, I came up with this C# code to delete cookies (and as a side effect it deletes all IE browser data).
public static void DeleteIECookiesAndData()
{
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "RunDll32.exe";
p.StartInfo.Arguments = "InetCpl.cpl,ClearMyTracksByProcess 2";
p.Start();
p.StandardOutput.ReadToEnd();
p.WaitForExit();
}
It isn't pretty at all, but it works. Maybe some pieces could be removed. (please let me know if you find a better way to do this).
IE Browser clears the cache for each element after every page load
ieCapabilities.setCapability(InternetExplorerDriver.ENABLE_ELEMENT_CACHE_CLEANUP, true);
This will do session clean up:
ieCapabilities.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);
Using java you can achieve that:
protected void deleteCookie(String cookieName) {
String cookieDomain = CTPropertiesManager.getProperty("site.properties", "site.cookie.domain");
try {
//get all cookies
Cookie cookies[] = request.getCookies();
Cookie ctCookie=null;
if (cookies !=null) {
for(int i=0; i<cookies.length; i++) {
ctCookie=cookies[i];
if (ctCookie.getName().trim().equals(cookieName)) {
if ( cookieDomain != null ) {
ctCookie.setDomain(cookieDomain);
}
ctCookie.setPath("/ct");
ctCookie.setMaxAge(0);
response.addCookie(ctCookie);
}
} //end for
}//end if cookie
} catch(Exception e) {
CTLogManager.log(e);
}
}//end deleteCookie()
For deleting cache
You can create one bat file which clear your browser or application cache before test start. after creating bat file just call in your code before test start.

C# WIA with Automatic Document Feeder (ADF) retuns only one page on certain scanners

I have a HP Scanjet 7000 (duplex & ADF scanner) and a HP Scanjet 5500c (only ADF) and a scanner program I'm developing which uses WIA 2.0 on Windows 7.
The problem is that the code works perfectly on the older scanner model, but on the newer one the code seems to run just fine through the first page, then fail on the second. If I step through the code around the following line;
image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatTIFF, false);
the old scanner stops and waits for another call to be made on the same reference, but the newer one just runs through all it's pages from the feeder in one continuous operation.
I notice if I'm using the default scanning program in Windows 7, the newer one returns a single .tif file which contains all the separate pages. The older one returns separate .jpg files (one for each page).
This indicates to me that the newer scanner is scanning through its whole feeder before it is ready to return a collection of images where the older one returns ONE image between each page scanned.
How can I support this behavior in code? The following is part of the relevant code which works on the older scanner model:
public static List<Image> Scan(string scannerId)
{
List<Image> images = new List<Image>();
List<String> tmp_imageList = new List<String>();
bool hasMorePages = true;
bool useAdf = true;
bool duplex = false;
int pages = 0;
string fileName = null;
string fileName_duplex = null;
WIA.DeviceManager manager = null;
WIA.Device device = null;
WIA.DeviceInfo device_infoHolder = null;
WIA.Item item = null;
WIA.ICommonDialog wiaCommonDialog = null;
manager = new WIA.DeviceManager();
// select the correct scanner using the provided scannerId parameter
foreach (WIA.DeviceInfo info in manager.DeviceInfos)
{
if (info.DeviceID == scannerId)
{
// Find scanner to connect to
device_infoHolder = info;
break;
}
}
while (hasMorePages)
{
wiaCommonDialog = new WIA.CommonDialog();
// Connect to scanner
device = device_infoHolder.Connect();
if (device.Items[1] != null)
{
item = device.Items[1] as WIA.Item;
try
{
if ((useAdf) || (duplex))
SetupADF(device, duplex); //Sets the right properties in WIA
WIA.ImageFile image = null;
WIA.ImageFile image_duplex = null;
// scan image
image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatTIFF, false);
if (duplex)
{
image_duplex = (ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatPNG, false);
}
// save (front) image to temp file
fileName = Path.GetTempFileName();
tmp_imageList.Add(fileName);
File.Delete(fileName);
image.SaveFile(fileName);
image = null;
// add file to images list
images.Add(Image.FromFile(fileName));
if (duplex)
{
fileName_duplex = Path.GetTempFileName();
tmp_imageList.Add(fileName_duplex);
File.Delete(fileName_duplex);
image_duplex.SaveFile(fileName_duplex);
image_duplex = null;
// add file_duplex to images list
images.Add(Image.FromFile(fileName_duplex));
}
if (useAdf || duplex)
{
hasMorePages = HasMorePages(device); //Returns true if the feeder has more pages
pages++;
}
}
catch (Exception exc)
{
throw exc;
}
finally
{
wiaCommonDialog = null;
manager = null;
item = null;
device = null;
}
}
}
device = null;
return images;
}
Any help on this issue would be very much appreciated! I can't seem to find a working solution on the web. Just unanswered forum posts from people with the same problem.
we had a very similar problem and various solutions, e.g. by setting certain properties, did not help. The main problem was that the scanner (ADF) retracted all pages on startup, regardless of what was happening in the program code.
The process repeatedly led to errors, since "too much" was made before the next page was scanned. This applies in particular to the fact that another "Connect" was attempted.
For this reason, we have modified the code so that the individual pages can be read in as quickly as possible:
public List<Image> Scan(string deviceID)
{
List<Image> images = new List<Image>();
WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog();
WIA.Device device = this.Connect(deviceID);
if (device == null)
return images;
WIA.Item item = device.Items[1] as WIA.Item;
List<WIA.ImageFile> wiaImages = new List<ImageFile>();
try
{
// scan images
do
{
WIA.ImageFile image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatJPEG, false);
wiaImages.Add(image);
} while (true);
}
catch (System.Runtime.InteropServices.COMException ex)
{
if ((uint)ex.ErrorCode != WIA_PROPERTIES.WIA_ERROR_PAPER_EMPTY)
throw ex;
}
catch (Exception ex)
{
throw ex;
}
foreach (WIA.ImageFile image in wiaImages)
this.DoImage(images, image);
return images;
}
I see you're calling a method called SetupADF, which is not shown, that presumably sets some properties on the device object. Have you tried setting WIA_DPS_PAGES (property 3096) and/or WIA_DPS_SCAN_AHEAD_PAGES (property 3094)?
I have a blog post about scanning from an ADF in Silverlight, and I believe a commenter came up against the same issue you're having. Setting WIA_DPS_PAGES to 1 fixed it for him. I ended up modifying my code's SetDeviceProperties method to set WIA_DPS_PAGES to 1 and WIA_DPS_SCAN_AHEAD_PAGES to 0.
After alot of trial and error I stumbled upon a solution which worked for reasons I'm not quite sure of. It seems like the ShowTransfer() method was unable to convert the page to .png or .tiff WHILE scanning. Setting the format to JPEG or BMP actually solved the issue for me:
image = (ImageFile)scanDialog.ShowTransfer(item, wiaFormatJPEG, false);
I think I saw somewhere on the web that this method actually returns BMP regardless of the format specified. Might be that converting the image to png or tiff is too heavy as opposed to using bmp or jpeg.
On a sidenote, I'm setting the property setting: 3088 to 0x005 (adf AND duplex mode).

Resources