How to check if monitor is on or off - java

I'm trying to know if is possible to understand if monitor is on or is off.
This is what i've tried:
GraphicsEnvironment g = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] devices = g.getScreenDevices();
int monitor_count = 0;
for(GraphicsDevice device : devices){
if(device.getType() == GraphicsDevice.TYPE_RASTER_SCREEN)
monitor_count++;
}
if(monitor_count==0){
System.out.println("Monitor is OFF");
}else{
System.out.println("Monitor is ON");
}
But even if i close monitor ( or disconnect directly from power ) it continue count me one monitor.
How can i know if monitor is OFF?

This is certainly not possible in cross platform Java, and to be honest isn't really possible in a reliable sense even if we resort to native code.
The (non-reliable) way to do this natively for Windows would be to use GetDevicePowerState - find it in kernel32.dll. However, from experiments I did using this function a while back I can say it definitely doesn't work with every monitor, and obviously even if this was reliable it would be a Windows-only solution.
If you do want to go down this route bearing in mind the above limitations, then use MonitorFromPoint to grab the handle to the primary monitor (pass in a 0,0 as the point and use the MONITOR_DEFAULTTOPRIMARY flag.)

Some information may be in operation system hands, especially for laptops - OS may get some notification if lid is open or closed. Most certainly not possible for VGA connector, maybe HDMI or DVI monitors report something back to the OS.
You should search for some OS specific functions, maybe something related to Power Management.

The only way to do it would be to have some sort of power usage monitoring device connected between the monitor and the outlet. Apart from that, I think even the computer can't tell if the monitor is on or off; only whether the signal lead is connected.
GraphicsEnvironment can only tell you the desktop arrangement that the user has configured at the OS level. It doesn't care whether there's a real monitor displaying it, or if it's a remote desktop connection, or if there's nothing.

The whole idea is flawed.
There is no way to tell for sure if a monitor is connected to lets say a VGA port, since it works one-way (output only). Although there is a way how the monitor can tell the computer about its capabilities added to VGA, but its completely optional.
Its different with HDMI (the devices actually need to talk to each other), but that doesn't necessarily mean that a monitor is connected to the port, even if the graphics card end believes that. It could very well be a recording device or anything other than a monitor.
The only cases where one could tell reliably if the display was on is when the display is built-in and controlled by the computer itself (e.g. laptop). Still the information is device specific and may not be available through any OS-calls.
Even if you manage to get an indication from the OS (as suggested through windows API), you can never rely on it to be correct. It will be the OS best guess and that will still be systematically wrong in some configurations.

Related

Swing Works different on different Platform

I have made a Screen Recorder using Java Swing and Xuggler 5.4. I have developed it in Windows 8 64 bit. It's working excellent for Windows. But at client side on Linux's environment , nothing is working. I have searched thoroughly but not getting any solutions. I have checked this thread , but it didn't work for me.
Then I tried to create simple Transparent window in Linux but it's also not working. I was not able to click through the Resizeable Panel. I have used the same JRE version (1.7) for both. Have I miss understood Java's Cross Platform Support as far as Swing is concerned?
Please Give Me Some Advice...
I have always found logging to be the best debugging tool at your disposal! Many a times, java debuggers take you into APIs where you need not go every time. Logging values of your variables, and generic 'I have reached till this point' statements make life a lot easier.
So, I suppose you have ample logging done in your code. That could give you clues on what's happening on your client's system.
Are the right environment variables set? Are they pointing to the correct Java versions you need.
If there are some specific Screen capturing requirements(plugins / modules / API) your code has, are they available on the Linux m/c?
Like #MadProgrammer said, in the end, Java has to talk with the native graphics APIs to render your screen.
I would try to debug it in this way -
Check whether my main screen loads or no(by disabling the screen capture functions for a while).
if not, dig deeper.
Check whether all necessary components for capturing screen(audio and video) are available.
Check whether the code is being run with appropriate permissions to control the h/w devices you may need.

In Java, is it possible to listen for the connection/disconnection of an external Monitor?

Upon disconnecting an external monitor from my laptop, I lose some of my apps as the disconnected monitor is still set as the default. Some of my windows are trying to display on the disconnected monitor.
I have a workaround, such as right clicking on the app icon and selecting move then using the arrow key to move the windows to my laptop. I'm wondering if there is a way in Java to listen for the disconnect, then reset my default screen to my laptop.
I thought about getting the number of and ID's of the screens that are available at startup and adding them to a property file. If a screen is disconnected, get the number of and ID's of the available screens again and compare those values to the values in my property file. I could then set the default to the screen that matches the new values and the stored values.
I haven't started coding this up yet. This is more investigative than anything at this point.
The AWT gives you access to screen information, although "external" is subjective as you might have 2 built-in monitors or 2 external ones.
At a basic level, you can count the monitors at any moment:
int numberOfMonitors = 0;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
for (int j = 0; j < gs.length; j++) {
GraphicsDevice gd = gs[j];
GraphicsConfiguration[] gc = gd.getConfigurations();
if (gc.getType() == TYPE_RASTER_SCREEN) numberOfMonitors++;
}
System.out.println("Number of monitors: " + numberOfMonitors);
To detect the attachment of a new monitor, you will need to poll for the result.
This is a pure Java solution; to my knowledge if you want anything more accurate than this then you'll probably need to call some native tools on the platform(s) you are targeting. For example, probing sysfs in Linux.
Basically I would say this is pretty hard or impossible to do with Java only. The reason is Java is a cross platform language and all this is handled by the underlying operating system. Please keep in mind, that it's hard to find a robust, cross platform solution for this problem.
You're asking how to detect, if a monitor is connected or disconnected:
Under Windows you can hook on WM_DEVICECHANGE via Java Native Access.
Maybe an idea is to check from time to time getScreenDevices() and detect changes, but this is more a workaround than a real solution.
You're also asking how you can change the primary display. There is an example how you can use the WinAPI for this task.
For other operating system you need to find other ways. I hope this answer gives an idea, that this could be quite hard to solve, especially with Java.
If you're targeting Windows with your Java app, there is a hardware workaround.
Connecting a monitor with a DisplayPort cable allows Windows to know when a display is off (be it by power button or disconnected cable). When Windows detects a monitor going offline, it moves all windows in the disconnected monitor to a screen that remains on. No extra coding needed. Although a limited use case, this could save you some trouble if you have control over the hardware.
On the other hand, if you code your own solution, you would do well to test your solution on this kind of setup to make sure the result of Windows moving windows around and your software moving windows around does not lead to unwanted behaviour.
(This is my experience on a Windows 10 box with NVIDIA/HP GPUs/monitors, YMMV)

Simulate Key Press at hardware level - Windows

I'm looking for a language or library to allow me to simulate key strokes at the maximum level possible, without physically pressing the key.
(My specific measure of the level of the keystroke is whether or not it will produce the same output as a physical Key Press when my computer is already running key listeners (such as MouseKeys and StickyKeys)).
I've tried many methods of keystroke emulation;
The java AWT library, Java win32api, python win32com sendKeys, python ctypes Key press, and many more libraries for python and Java, but none of them simulate the key stroke at a close enough level to actual hardware.
(When Windows MouseKeys is active, sending a key stroke of a colon, semi colon or numpad ADD key just produces those characters, where as a physical press performs the MouseKeys click)
I believe such methods must involve sending the strokes straight to an application, rather than passing them just to the OS.
I'm coming to the idea that no library for these high (above OS code) level languages will produce anything adequate. I fear I might have to stoop to some kind of BIOS programming.
Does anybody have any useful information on the matter whatsoever?
How would I go about emulating key presses in lower level languages?
Should I be looking for a my-hardware-specific solution (some kind of Fujitsu hardware API)?
I almost feel it would be easier to program a robot to simply sit by the hardware and press the keys.
Thanks!
Second solution, super convoluted, a ton of virtualization, diabolical, totally untested, but theoretically should work, unless the datasnip program doesn't actually write to the keyboard buffer, but instead simulates keystrokes like you've been trying to. That would suck, and I would find the description of their product to be highly misleading.
You'll need:
http://www.priority1design.com.au/datasnip.html
http://sourceforge.net/projects/com0com/
And some knowledge of writing to com ports... which, looks like there's a good python module here: http://pyserial.sourceforge.net/
First, write a small program that will send characters, hexcode, etc. as necessary to the COM port of your choosing. Second, create a virtual COM port pair using com0com. At this point, connect your program to one of the COM ports created, and datasnip to the other, making sure that both sides of the communication are using identical baud rates, parity and stop bits, and data length parameters.
At this point you should have a keyboard that is identical to a hardware one, as far as the OS can tell.
I used this solution http://oblita.com/interception.html
It fully meets my needs (sending keystrokes to direct input game)
Can you use an MSDN language? They're fairly simple and well documented (google searches are better than the msdn website, for navigation, usually)
I found this bit, and I couldn't tell you if it simulates keystrokes at a level close enough to the hardware, but it does appear to be able to generate keystroke events that other programs can recognize, which is what your ultimate goal is.
http://msdn.microsoft.com/en-us/library/ms171548.aspx
The 'Send' and 'SendWait' Methods seem to be the key ones.
http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.sendwait.aspx
Godspeed.
I'm not on a Windows box to test it against MouseKeys, so no guarantees that it will work, but have you tried AutoHotkey?

Screensharing via Java Applet

I am looking for an addition for our "livestream and podcast" solution, which uses a camera to film speeches in our house.
It has been requested to view the slides of our speakers directly as a image in the webbrowser instead of the video stream. We don't want/can not install software on the speakers laptop, so I thought about a Java applet, which the speaker can just run via a webbrowser.
So what I need is technically this:
[speakers laptop] -> [Screencapture every N seconds via applet on a webpage] -> [Displaying the screen of the speaker on a different webpage for the external viewers]
I know there are Java applications which do record the screen, but save the file output locally. I need something that does the same, but sends the image to the server. On the server side I thought about a websocket.js accepting and displaying the image (other suggestions are welcome).
It would be great if somebody could help me out here. Btw, I never programmed in Java, so telling me which frameworks I need won't really help me.
Thanks!!
I was recently asked to evaluate possibilities for live screen-cast via applet. Most video APIs do not support codecs that have high enough compression (e.g. JMF). Some APIs can do advanced formats (JFFMPEG, Xuggle) but also use natives. While natives are normally no problem for an app. launched (free floating) using Java Web Start or a Plug-In 2 applet, the makers of Xuggle identify 'the order of loading natives' as a problem (e.g. won't work) for both JWS and applets.
It is a pity that more than a decade into its development, Java has no reasonable API for video capture/processing that can be deployed for a wide use (applet/JWS based - for the 'general public') GUI.
Perhaps you can find a solution using Flash.
Update 1
In fact, I do not need the screen to be recorded as a video.
In fact, you mentioned much of that in your initial question, but I focused on just a few keywords before drafting a reply. My bad. :P
OK.
Getting an image is relatively easy. An applet would need to be trusted in order to get a screenshot, but once trusted, it is just a few lines of code to get the image.
Encoding the image to JPEG of particular quality/compression setting (in memory) is also doable.
Sending the image to the server would depend on the size in bytes and connection speed, but one image with a high compression, every 10 seconds, should be doable. The server would need to implement functionality to accept the image.
As far as displaying the image on the client, it seems you already have some ideas based around JS. If you can make that work that would be optimal, since it can then be viewed in browsers with no Java.
I would still recommend you deploy the app. to the 'speaker' using Java Web Start, rather than embed an applet. A JWS app. will give you less deployment & maintenance troubles, and the JWS launch is ..nicer. Further, a free floating frame launched using JWS can minimize itself (or in later JREs, become transparent), during the action of taking a screen image - thereby capturing everything on the screen except itself.
Update 2
I actually found this code here.
That is ..horrible. Not the code, the site. When I visited it I got a message saying a pop-up had been suppressed (fair enough). Then there was the irritating 'vibrating dialog' hovering in the middle of the page (and following the scroll). You click the little x to see - another tab opened with yet another floating dialog, saying some other rubbish about how "You've won.." - with sound loud enough to drown out my high volume trance/dance playlist.
Then after closing that the hell out of my FF, I go back to the original page, close the damn 'dialog', scroll down & see.. a red background to the code (shudder). That is as far as I could manage. I closed the page with the code.
Try this code instead, for a single screen-shot.
Would it be possible to use this on the client side..
Yes.
.. and receive it with javascript on the server side?
Not really. Unless you mean an IIS based server running Microsoft's JScript. JavaScript is a client side technology.
For security reasons, servers need to protect themselves. E.G. From:
Someone creating a slavebot that uploads all the 1000s of docs on the slave machine's to the site - to make it crash.
People high-jacking your server for storing and serving bestiality porn (or worse).
Because of things like that (bad people have lots of imagination), while servers can easily accept uploads, they are generally not configured by default to allow them.
.. (I don't want Java on my server ;-)
It can be done using PHP, ASP, CGI etc. It does not need Java specifically, but it does need some active involvement from the server, if only to check the size of what is being uploaded and abort if it gets too large!
..Will take a look at the link you posted, but as I said, I can't program in Java, though I can understand some of it. Thanks!
It sounds like you'll need some help getting the server-side of it ready, as well. It is trivial for someone that knows how (not me), but a potential security nightmare for the inexperienced.
Update 3
where do I add the function to send the picture?
Sorry. I've not tried to implement that - you'd want to want to encode it to JPEG before sending, to reduce the size. See this code for how to provide an adjustable compression/quality where the user can see the effect.
There are various ways to get an image to a server. E.G. sockets, HTTP, FTP.. AFAIU it would depend on how the server is accepting it. I am unfamiliar with the specific term 'websocket' or the node.js script. Can you link to what you mean?
..the old code added to pastebin, so it's readable
Smart thinking. I notice it uses sockets, it was in the back of my mind that sockets would be best for this, since they have low overhead and short wait times.

How can I handle multiple mouse inputs in Java?

A friend of mine asked me to implement a blue and a red pointer to represent the inputs of two separate mice to expedite a mixing desk scenario for real time audio mixing. I'd love to, but as much as I think it is a great idea, I don't have a clue as to where to start looking for a possible solution.
Where should I start researching a viable method of implementing dual mouse inputs?
Look at jinput.
I have had multiple keyboards working with it, I am nearly certain it supports multiple mice too.
dont know about java.. but for C#/c++ you can try the
Microsoft Windows MultiPoint Software Development Kit
i've tried it on windows.. it works with 2 USB mice.
It depends on which operating system you intend to use.
On Windows, you can use:
CPNMouse - a driver+software combination, very flexible and allows to completely hide some of the mice from the operating system.
RawInput - an API provided by Windows XP only. You can use it to distinguish between two mouse inputs, draw the cursors yourself and hide the main cursor. Take a look at the code of SDGT, a C# usage of this API.
For both solutions you would have to build a JNI bridge to your application
If you are using X.Org (X11) server, there is patched version called MPX that should support multiple mice even for legacy applications. It should now be a part of the X.Org trunk, but I'm not very familiar with it. Anyway it has an API so you can use it via JNI bridge.
You can use multiple devices, but at the Java level, all mouse events are coalesced into a single stream. The event does not include which mouse it came from. You did say you wanted to mix audio, right? Well this mix might be interesting, but surely not what you want.
I'd suggest using the Java-supported midi interface and connecting some simple midi controller device with multiple knobs or trackballs. These will come in as midi events, and you can examine the state for the details you need.

Categories

Resources