Matlab - signal after command completion - windows

Is there a way to set matlab to come to the foreground of the windows when the command in complete? I can see it happening by executing a dos() but I'm unaware how window management works? Maybe there is a better way? Someone?

Two options. Neither exactly what you are asking for.
Option 1: Open a new figure.
figure();
imagesc(processingDoneSplashImage);
If you want to get fancy, put this in a script, with a timer, and flash the image between bright green, and bright red....
Option 2: My solution to your problem. (I find popping up windows extremely annoying.) I put this function call at the end of my long running scripts, and the computer tells me when it's done processing....
function [ ] = matSpeak( textToSpeak )
%matSpeak takes some text, and outputs onto the speaker the text,
% using the .Net SpeechSynthesizer.
% This only works on Windoze.
if ~exist('textToSpeak','var')
textToSpeak = 'Your processing has completed.';
end
NET.addAssembly('System.Speech');
speak = System.Speech.Synthesis.SpeechSynthesizer;
speak.Volume = 100;
speak.Speak(textToSpeak);
end

Why not just use Growl for your notification windows?
cmd = ['/usr/local/bin/growlnotify -m ' messagestr];
system(cmd);
Of course with Windows you need to fix the path to the growlnotify binary.
Source: http://www.mathworks.com/matlabcentral/newsreader/view_thread/259142
A wrapper with lots of features: Send a notification to Growl on MATLAB Exchange
Many more examples: https://www.google.com/search?q=growl+matlab

Related

Control brightness in Windows at software Level

It might be possible for a similar question to be already present on the site, but I have searched a lot and didn't find any relevant solution, so I'm posting it here.
I'm making a Night Light Application, which has two options-
Lessen the Brightness of the PC
Apply a Blue light filter mask over the screen.
I'm making this app cross platform, so I've already found a solution for Linux Systems, where I've been making use of xrandr utility to adjust the brightness and gamma at the software level, and my app works flawlessly.
The main problem is for Windows systems, where the brightness feature is only available for portable screens such as for a Laptop.
I cannot find any solution for this.
I made use of Qt5 for making a translucent app window which works good, but doesn't meet the requirement because the things displayed at kernel level are not masked like the cursor, taskbar, start menu, action center, and lots of other.
I searched a lot and lot, which included Microsoft Developer Network, where documentation included the Win32 API where brightness feature was present, but it didn't work for me, as I had a Desktop PC.
So my main problem is, How can I ajust the brightness of all Windows PC, including Laptops, Desktops n all others.
I'm working on Python with ctypes module.
I'm not that much familiar with VC+ and I cannot even afford to install it on my system as it is too much storage and resource intensive.
I primarily want to modify the output going to the physical monitor, that is to modify the Gamma values to get appropriate brightness and Yellow tincture.
I got something called gdi32.dll which deals with the outputs to screens, but I cannot find a way out as everything on the Internet is alongside C++.
Also, I cannot even provide my try code, as I'm not that much familiar to C type coding in Python.
Also, the thing I want to do, Intel Graphics Command Center already does it on my desktop.
If it can do it on at a software level, then I know its possible programmatically.
Can anyone tell is this possible what I'm thinking, and if yes, how can I achieve this?
I don't want the source code, I just want the way out for that.
Maybe GammaRamp from the Gdi32 API can be used, but I don't know how to begin.
This is a thread which actually asked this, but I didn't get my answer from here, and newbies are restricted from commenting, so I didn't have any choice than to post this question here.
I have found the way for the problem.
We can use GetDeviceGammaRamp and SetDeviceGammaRamp from the gdi32.dll library in Windows OS to set the brightness level.
To call these functions through Python, we can use ctypes module.
Below is the sample code that can set brightness of in Windows 10 via Python.
import ctypes
def displayGammaValues(lpRamp):
"""
Displays the GammaArray of 256 values of R,G,B individually
:param lpRamp: GammaArray
:return: None
"""
print("R values: ", end=' ')
for j in range(256):
print(lpRamp[0][j], end=' ')
print()
print("G values: ", end=' ')
for j in range(256):
print(lpRamp[0][j], end=' ')
print()
print("B values: ", end=' ')
for j in range(256):
print(lpRamp[0][j], end=' ')
print(), print()
def changeGammaValues(lpRamp, brightness):
"""
Modifies the Gamma Values array according to specified 'Brightness' value
To reset the gamma values to default, call this method with 'Brightness' as 128
:param lpRamp: GammaArray
:param brightness: Value of brightness between 0-255
:return: Modified GammaValue Array
"""
for i in range(256):
iValue = i * (brightness + 128)
if iValue > 65535: iValue = 65535
lpRamp[0][i] = lpRamp[1][i] = lpRamp[2][i] = iValue
return lpRamp
if __name__ == '__main__':
brightness = 100 # can be aby value in 0-255 (as per my system)
GetDC = ctypes.windll.user32.GetDC
ReleaseDC = ctypes.windll.user32.ReleaseDC
SetDeviceGammaRamp = ctypes.windll.gdi32.SetDeviceGammaRamp
GetDeviceGammaRamp = ctypes.windll.gdi32.GetDeviceGammaRamp
hdc = ctypes.wintypes.HDC(GetDC(None))
if hdc:
GammaArray = ((ctypes.wintypes.WORD * 256) * 3)()
if GetDeviceGammaRamp(hdc, ctypes.byref(GammaArray)):
print("Current Gamma Ramp Values are:")
displayGammaValues(GammaArray)
GammaArray = changeGammaValues(GammaArray, brightness)
print("New Current Gamma Ramp Values are:")
displayGammaValues(GammaArray)
if SetDeviceGammaRamp(hdc, ctypes.byref(GammaArray)): print("Values set successfully!")
else: print("Unable to set GammaRamp")
if ReleaseDC(hdc): print("HDC released")
else: print("HDC not found")
This sets the brightness value, that's between 0-255. Values may differ system-to-system, so preferable range for brightness is 0 - 128 where 128 is the default brightness.
FYI windows already has a monitor blue shade/color shift built in. Dimming external monitor outputs on a desktop is likely not possible.
You'll need to hook into the windows API somehow to control windows functions. There's some documentation about adjusting color temperature (making that warmer would essentially add a "blue light" filter to a screen on microsoft's website.
https://learn.microsoft.com/en-us/windows/win32/api/highlevelmonitorconfigurationapi/nf-highlevelmonitorconfigurationapi-setmonitorcolortemperature.
In terms of executing a small CPP script that actually can interface with windows, you can write a small CPP program, then compile it and execute from python using (slightly modified from this question)
import os
import subprocess
for filename in os.listdir(os.getcwd()):
proc = subprocess.Popen(["./prog", filename])
proc.wait()
However if you don't have the room to install visual studio compile tools, you won't be able to compile a small CPP script locally. There are a few online services that would be able to do that for you though.

how can i make AutoIT send command reliable?

Hi guys I'm running a script with AutoIt to insert the path of a file to upload with webdriver.
But the send command is so unreliable it's 50/50 it messes up the characters and the script just stops.
Is there a way to make it reliably input the data? Or maybe how can i confirm that the input is correct, resend, and then send?
This is what i have for the code. It sends the input into the firefox upload window.
WinWaitActive("File Upload")
Send("C:\Users\elsid\Desktop\Eclipse\Workspace\NG - Mentored\Autoit\Test.png")
Send("{ENTER}")
Thanks
The most reliable way is to use ControlSetText.
Play with AutoitWindowInfo tool and tweak the script below if needed.
#RequireAdmin ;Will give your script a permission elevation (sometimes its needed)
Opt("WinTitleMatchMode", 1) ;1=start, 2=subStr, 3=exact, 4=advanced, -1 to -4=Nocase
Opt("WinSearchChildren", 1) ;0=no, 1=search children also
WinActivate("File Upload")
WinWaitActive("File Upload","",10)
ControlFocus("File Upload","","Edit1")
Sleep(2000)
ControlSetText("File Upload","","Edit1","dropdowns.jpg")
In my humble opinion, the script stops because it waits that the window will be focused. To not messes up the characters, use function flag 1 in Send().
Try this way:
While WinWait("File Upload","",1) = 0
Sleep(500)
WEnd
WinActivate("File Upload")
Send("C:\Users\elsid\Desktop\Eclipse\Workspace\NG - Mentored\Autoit\Test.png", 1) ;-- flag 1 = keys are sent raw.
Send("{ENTER}")
Good Luck ;)

Is there a way to make an existing cmd window execute commands?

So here is my situtation.
I am using the Windows OS. I am running a Matlab GUI that launches another executable at startup. The other executable runs in batch mode (runs in cmd in the background).
I want to make it so when a user clicks a button on the Matlab GUI, the other executable will run a command and remain open. Is this possible?
NOTE: I do not want to open a new cmd window, I want the existing one to execute commands.
Unfortunately it does not appear that Matlab has the ability you are looking for, at least not directly. I found a post which does explain how to do it with the help of .NET though, which is fortunate since you are on the Windows platform: http://www.mathworks.com/matlabcentral/answers/72356-using-matlab-to-send-strings-to-the-stdin-of-another-console-application
I have copied a lot of this from that post
function lh = task()
% Initialize the process and its StartInfo properties.
% The sort command is a console application that
% reads and sorts text input.
process = System.Diagnostics.Process;
process.StartInfo.FileName = 'sort.exe';
process.EnableRaisingEvents = true;
process.StartInfo.CreateNoWindow = true;
% Set UseShellExecute to false for redirection.
process.StartInfo.UseShellExecute = false;
%Redirect the standard output of the sort command.
process.StartInfo.RedirectStandardOutput = true;
% Set our event handler to asynchronously read the sort output.
lh = process.addlistener('OutputDataReceived',#sortOutputHandler);
% Redirect standard input as well. This stream
% is used synchronously.
process.StartInfo.RedirectStandardInput =true;
% Start the process.
process.Start();
%Use a stream writer to synchronously write the sort input.
ProcessStreamWriter = process.StandardInput;
% Start the asynchronous read of the sort output stream.
process.BeginOutputReadLine();
%Prompt the user for 4 input text lines. Write each
%line to the redirected input stream of the sort command.
numInputLines = 0;
while(numInputLines ~= 4)
inputText = input('Enter a text line (or press the Enter key to stop):', 's');
numInputLines = numInputLines + 1;
if(~isempty(inputText))
ProcessStreamWriter.WriteLine(inputText);
end
end
disp('end of input stream');
%end the inputr stream to the sort command
ProcessStreamWriter.Close();
% wait for the sort process to write the sorted text lines
process.WaitForExit();
process.Close();
end
For handling any output from the CMD you need:
function processOutputHandler(obj,event)
%collect the sort command output and print in command window
if(~isempty(event.Data))
disp(event.Data);
end
end
You can use a stream writer to synchronously write the sort input.
processStreamWriter = process.StandardInput;
Again, I have taken this from the previously mentioned post so I can't take any credit for the code, but I do think it will be able to accomplish what you are looking for. Unfortunately, I am pretty sure this will accomplish what you need. I don't have Matlab on a Windows platform at the moment or I would test this. If you need information on using .NET code in MATLAB (its not immediately clear if you need to add some stuff to establish the .NET interface) MathWorks provides some documentation on it: http://www.mathworks.com/help/matlab/matlab_external/using-net-from-matlab-an-overview.html
Hopefully this helps, or gets you started. Let me know if there's anything else I missed.
You can approach this from the ansys side. Start it with -B-R to read a python script.
From there, you can establish some two-way protocol, for example polling files or, better, by running a web server from python.
Then you can communicate from matlab with that running instance of ansys. If you opt for a web server, you use MATLABs urlread().
Setting up a web-server with python is easy, but you have to learn how to dispatch commands to the hosting ansys application.

Interrupt MATLAB programmatically on Windows

When using MATLAB through the GUI, I can interrupt a computation by pressing Ctrl-C.
Is there a way to do the same programmatically when using MATLAB through the MATLAB Engine C API?
On Unix systems there is a solution: send a SIGINT signal. This will not kill MATLAB. It'll only interrupt the computation. I am looking for a solution that works on Windows.
Clarifications (seeing that the only answerer misunderstood):
I am looking for a way to interrupt any MATLAB calculation, without having control over the MATLAB code that is being run. I'm looking for the programmatic equivalent of pressing Ctrl-C in at the MATLAB command window, on Windows systems. This is for a Mathematica-MATLAB interface: I need to forward interrupts from Mathematica to MATLAB. As mentioned above, I already have a working implementation on Unix; this question is about how to do it on Windows.
One way would be to make the MATLAB Engine session visible, prior to executing long computations. That way if you want to interrupt execution, you just bring the visible command window into focus and hit Ctrl-C.
This can be done using the engSetVisible function
Here is a quick example I tried using MATLAB COM Automation. The process should be similar since MATLAB Engine is implemented using COM on Windows (pipes are used on Unix instead).
The scripting is done in Powershell:
# create MATLAB automation server
$m = New-Object -ComObject matlab.application
$m | Get-Member
# make the command window visible
$m.Visible = $true
# execute some long computation: pause(10)
$m.Feval('disp', 0,[ref]$null, 'Press Ctrl-C to interrupt...')
$m.Feval('pause', 0,[ref]$null, 10)
# close and cleanup
$m.Quit()
$m = $null
Remove-Variable m
During the pause, you can break it by hitting Ctrl+c in the command window:
There isn't a direct way: all of those routines have to be unwound and their workspaces
cleaned up, which might invoke exit handlers, and so on.
The closest I can think of is to have your main routine have a try/catch
and then when you wish to abort, error() the particular string that the
catch is keyed for, and when you detect it, bail out cleanly from your
main routine.

how to kill orphaned winword.exe in matlab

Running matlab R2010B on Windows 7 Enterprise
In matlab scripts, I save a bunch of results to a word file and then at the end, close and quit word. The code I use is:
WordFname = ['BatInfoDoc' sprintf('%0.3f',now) '.doc']; % serialnumbered filenames
WordFile = fullfile(pwd,WordFname);
WordApp = actxserver('Word.Application');
WordDoc = WordApp.Documents.Add;
WordDoc.SaveAs2(WordFile);
....
WordApp.Selection.TypeText([title2 title3 title4 title5 title6]);
WordApp.Selection.TypeParagraph;
then finally at the end of the script
WordDoc.Close;
WordApp.Quit;
The problem I have is that through my development process, I often crash the matlab script and wind up leaving orphaned WINWORD.EXE processes, each one of which keeps a lock on the file it had been writing.
Up until now I have been using TaskManager to kill these processes one at a time by hand. Having been developing all morning, I find myself with around 20 files I can't delete because they are locked by about 11 orphaned WINWORD.EXE processes!
My question(s):
1) Is there an elegant way to handle the file writing and saving and closing and so on so I don't lock up files and processes when my script crashes out before I get to the part where I close the file and quit word?
2) Is there an elegant way to determine the bad processes from within matlab script and go through and delete them from within a matlab script? That is, can I code my matlab so it cleans up after itself?
ADDED A FEW MINUTES LATER:
By the way, I would prefer NOT to enclose all my code in a big try-catch and then close the windows after I've caught my error. The problem with this is I do like to go to debug mode on error, and caught errors don't bring me to debug mode.
Straight after you create Wordapp, use c = onCleanup(#()Wordapp.Quit). When your function exits, either naturally or with a crash, c will be deleted and its function will execute, quitting Word. If this is part of a script rather than a function, you can manually delete c to quit.
Also - while developing/debugging, I would set Wordapp.Visible to true so you can manually close word if necessary. Set back to false for production.
Use a handle class to delete them automatically.
classdef SafeWord < handle
properties(Access=public)
WordApp;
end
methods(Access=public)
function this = SafeWord(WordApp)
this.WordApp= WordApp;
end
function delete(this)
this.WordDoc.Close;
this.WordApp.Quit;
end
end
end
And the use case:
sw = SafeWord(Word.Application());
WordApplication = sw.WordApp;
% Do something here
% When sw ends its lifecycle, it calls delete.
Here is a related question.

Resources