Java TrayIcon.displayMessage() does not work on Windows XP - java

I'm writing an application that runs in the System Tray and notifies the user (i.e. makes one of those bubbles pop up) when something happens. The only problem is that the notifications only seem to work on Windows 7, and not Windows XP.
I've tested it on 2 Windows 7 computers (they've both worked) and 4 Windows XP computers (none of them have worked). No notification bubble is shown, and (as far as I know) no exceptions are thrown and everything else works as it should. I've even tested it on a Mac, and it worked, but it wasn't too pretty.
Here is a sample of my code.
private static TrayIcon trayIcon;
...
trayIcon = new TrayIcon(trayImage.getImage());
...
if (!SystemTray.isSupported())
{
System.out.println("SystemTray is not supported");
return;
}
final PopupMenu popup = new PopupMenu();
final SystemTray tray = SystemTray.getSystemTray();
trayIcon.setToolTip("Widget Name Here [" + role + "]");
...
try
{
tray.add(trayIcon);
}
catch (AWTException e)
{
System.err.println("TrayIcon could not be added.");
return;
}
...
//Here's where it doesn't work on XP
trayIcon.displayMessage("Connection error",
"Could not connect to server, please check your internet/VPN "
+ "connection", TrayIcon.MessageType.ERROR);
Any help would be much appreciated.
UPDATE: Ok, I've just confirmed that it's not a problem with my program, but a problem with the XP installations I've been testing them on. I ran the TrayIconDemo.java program found here on an XP computer and none of the notifications worked. I'm starting to think there's nothing I can do to get it to work on one of these computers...

Okay, so I've finally found the solution to my problem. It turned out that the following key was set to 0 (false) by default on the installations I was testing on:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced\EnableBalloonTips
To enable the notification bubbles, simply set the value to 1.

I have Windows XP and working on system tray application. I have just added displayMessage() and it works just fine for me. Try to simplify your application. I am sure it will work. The find a bug.

EDIT: you didn't mentioned JRE version System try required Java6
this should be comment, but this is restrict for chars lenght
maybe, there is another reason in case of when Java updates are distributed by some of administrations tool for AD or ZenWorks, then sometimes (on both win7/Xp) is needed un-install all java instalactions and install fresh JRE manually (but stable 1.6.022 my view), sw distibutions ends without error, but all (???) classes/methods/changes cames from Java6 weren't accesible, on partial (RowSorter etc...) test ends with error, and I never search for knows Bugs on MS, Novell ...

Related

lwjgl 3 macOS issue with creating windows

I created some code to work with lwjgl3, and ran into an issue with the macOS bindings since I am working on a mac.
The issue is that I cannot seem to get my program to create any windows. I know this for sure as the program just stops at that point. There are no errors.
The line the code gets stuck on is:
long window = glfwCreateWindow(300, 300, "Hello World!", MemoryUtil.NULL, MemoryUtil.NULL);
Since I am developing on IntelliJ, whenever I disconnect the process, it crashes with :
Exception Type: EXC_BAD_ACCESS (SIGABRT)
Exception Codes: EXC_I386_GPFLT
Exception Note: EXC_CORPSE_NOTIFY
I feel that that is not the issue, as I tried running another code dependant on lwjgl3, and it also got stuck at the part creating the window.
I know that the code is stuck at the part to create the window as I have put print statements every line.
I really hope that this is not a compatibility issue with either macOS Big Sur or the mac book pro 2015 model.
while glfwInit() return true, when I run System.out.println(glGetString(GL_VERSION) );, I get this error Fatal error: Thread[main,5,main]: No context is current or a function that is not available in the current context was called. The JVM will abort execution.
Here is the complete code that I am using for testing:
public static void main(String[] args) throws Exception{
GLFWErrorCallback.createPrint(System.err).set();
// Initialize GLFW. Most GLFW functions will not work before doing this.
if ( !glfwInit() )
throw new IllegalStateException("Unable to initialize GLFW");
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
// Configure GLFW
glfwDefaultWindowHints(); // optional, the current window hints are already the default
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); // the window will stay hidden after creation
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); // the window will be resizable
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
// Should be true for macOS, according to GLFW docs, to get core profile.
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
// According to Apple docs, non-core profiles are limited to version 2.1.
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// Create the window
long window = glfwCreateWindow(300, 300, "Hello World!", MemoryUtil.NULL, MemoryUtil.NULL);
//glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
System.out.println('0');
glfwDestroyWindow(window);
}
I have googled this multiple times:
cannot seem to find a relevant answer. One person suggested that macOS has a hidden popup that had to be closed for the window to be assigned, but I did everything to disable it (as I could not find it) and still nothing happened. I think the GL_VERSION indicates an issue with how openGL is being bound to Java.
[Edit]
Ensured that the app was running on the main thread by passing in the JVM option -XstartOnFirstThread.
[EDIT2]
After leaving the project for a few hours, I came back and reran it.
I added one extra line on the top:
System.out.println("Hello LWJGL " + Version.getVersion() + "!");
The createWindow(...) function started working, which is weird as I do not know why. It also started working if I removed the line, so if anyone knows what was happening please let me know.
I am leaving the question unanswered as I still do not know the reason for the issue, I just happened to be lucky that it fixed itself.
[EDIT3]
I force rebuilt the entire project on intellij and it stopped working again. Am really confused as to why it was working in between
I had the -XstartOnFirstThread on the gradle.properties. Try set it in the jvmargs of the run configuration you currently have. That fixed it for me

Detect dark windows taskbar

For theming purposes, I'm looking to detect the color of the Windows taskbar (in my case, for a tray icon).
I'm using Java, but any solutions are welcome as I'd happily convert them over as needed.
My first attempt was to read the registry.
This worked great for desktops that provided this value, but falls
short when the registry
does not provide it.
My second attempt was to take a screenshot of the taskbar and try to guess if it's dark or light themed.
This even works when autohide is on. Unfortunately it returns a black background regardless of what I do:
WinDef.HWND tray = User32.INSTANCE.FindWindow("Shell_TrayWnd", null);
BufferedImage bi = GDI32Util.getScreenshot(tray);
SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(null, new JLabel((new ImageIcon(bi)))));
Assuming I don't want to rely on the white/black color of the Windows logo, is there a way to detect this?
Related:
How can I detect Windows 10 light/dark mode?
How do I get the mode (Light/Dark) of the PC in C#?
How can I get whether Windows 10 Anniversary Update or later is using its light or dark theme in a WPF app?
Similar (10 year old) question on MSDN
So far, I have not encountered the lack of SystemUsesLightTheme and AppsUseLightTheme in the registry.
But I think recreating the key-values is worth trying.
Here is code sample(C++):
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <Windows.h>
using namespace std;
int main() {
HKEY key;
if (RegOpenKey(HKEY_CURRENT_USER, TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"), &key) != ERROR_SUCCESS)
{
cout << "unable to open registry";
}
DWORD value_data = 0;
if (RegSetValueEx(key, TEXT("SystemUsesLightTheme"), 0, REG_DWORD, (const BYTE*)&value_data, sizeof(value_data)) != ERROR_SUCCESS)
{
RegCloseKey(key);
cout << "Unable to set registry value value_name";
}
else
{
cout << "value_name was set" << endl;
}
}
When the documented registry entries are missing, it appears something in the OS is coded to fallback the following settings:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize\
If AppsUseLightTheme is missing, assume it's 1
... and then make the dark/light Windowing decisions based on this value.
If SystemUsesLightTheme is missing, assume it's 0
... and then make the dark/light Taskbar/SystemTray decisions based on the this value.
The glory details...
Although fresh Windows Home installs defaults to the Light theme, these fresh installers also set the registry keys properly, so the combination of a missing registry key and a light taskbar is extremely unlikely (and probably impossible). To a similar point, studying modern OSs may -- improperly -- suggest the defaults come from the file C:\Windows\resources\Themes\aero.theme**, but don't be fooled! Older OSs didn't have a differentiating entry either... More below.
Instinct would suggest that the CurrentTheme or perhaps the InstallTheme registry values would serve as a sane fallback value, but changing these values appear to be for historical purposes and do not appear to actually change the light/dark theme.
reg query HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Themes /v InstallTheme
>>> returns the path to aero.theme
type %SystemRoot%\resources\Themes\aero.theme |find "SystemMode"
>>> returns SystemMode=dark
Even changing the InstallTheme for the entire machine (HKEY_LOCAL_MACHINE) doesn't modify this behavior of preferring SystemMode=dark (note, even this entry wasn't available in older Windows 10 versions. For example, Windows 10 v1507 doesn't have this entry in the theme file either).
Chasing the aero.theme hit some dead ends too. Attempts to directly modify aero.theme failed due to permissions, but copying aero.theme to the Desktop and changing SystemMode=dark to SystemMode=light and then double-clicking the theme file will make the taskbar go white, but only on newer Windows versions that supported the light theme.
So, yes, I have to agree with #strive-sun-msft the SystemUsesLightTheme registry entry is the best location. When testing, even the Task Bar itself monitors this, deleting it will reset it back to black. Unfortunately that fallback black Task Bar color remains to be a mystery. I can only assume it's hard-coded into the task bar itself.
Another workaround for this behavior is to just install the aero.theme file again by running it if the registry entries are missing. On newer Windows 10 versions, simply running this file will create the missing entries. Unfortunately, this doesn't work on older Windows 10 versions and worse, this will reset any custom preferences set by the user.
So the least intrusive way to detect the color of the taskbar is to read the registry and if the keys are missing, simply assume the theme Windows 10 shipped with is still in effect: Dark Taskbar, Light Windows.
You can use the Windows Registry Value SystemUsesLightTheme that is available at this Registry Path: Software\Microsoft\Windows\CurrentVersion\Themes\Personalize
for detecting the dark/light theme.
I found a library called JRegistry that allows you to access
this value.
RegistryKey windowsPersonalizeKey = new RegistryKey("Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize");
RegistryValue systemUsesLightThemeValue = windowsPersonalizeKey.getValue("SystemUsesLightTheme");
if (systemUsesLightThemeValue != null) {
//this value is available
//getting the actual value
byte[] data = systemUsesLightThemeValue.getByteData();
byte actualValue = data[0];
boolean windows10Dark = actualValue == 0;
if (windows10Dark) {
//the theme is dark
} else {
// the theme is light
}
}
Also, if you want to listen to this value dynamically:
RegistryKey registryKey = new RegistryKey("Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize");
RegistryWatcher.addRegistryListener((RegistryEvent registryEvent) -> {
RegistryKey changedKey = registryEvent.getKey();
if (changedKey.equals(registryKey)) {
RegistryValue value = changedKey.getValue("SystemUsesLightTheme");
//....
}
});
RegistryWatcher.watchKey(registryKey);

JavaFX still truncates the Alert messages

I am trying to show an Alert with a long message, and it tends to get truncated at a word boundary.
I think it's only a Windows and Linux issue. I found some answers that propose this solution: alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE);.
Or this one:
alert.getDialogPane().getChildren().stream().filter(node -> node instanceof Label).forEach(node -> ((Label)node).setMinHeight(Region.USE_PREF_SIZE));
However, I still have the same problem on my CentOS.
Alert alert = new Alert(AlertType.CONFIRMATION, Messages.AoiPanel_confirmation_message, ButtonType.YES, ButtonType.NO);
alert.setTitle("");
alert.initOwner(deleteButton.getScene().getWindow());
alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE);
alert.showAndWait();
This is what I mean by get truncated at a word boundary (sorry I can't share the image of the real application as my centOS is a secure OS and the application is private).
If it helps, I use win7 + java 1.8.0_102 and xubuntu + java 1.8.0_111 and the text is only truncated after 12 lines. But because the alert dialog doesn't seem to extend horizontally by default and most of the messages in my project are rather long, I also use...
alert.getDialogPane().setMinWidth(600);
... so I don't have that problem any more.

How can I prevent the Charm bar from showing up in my Java application?

I've got a Java swing program that runs in full screen mode. It's effectively a kiosk program in that I want it to lock out everything else while it's running. This is running on a Windows 8.1 tablet, so of course the tablet is touchscreen, and therefore if you do an "edge swipe" (drag your finger from the right) the charms bar pops up and you can get to the Start screen from there. Is there some way to disable this from happening in Java? (Or is there some third-party solution not involving Java that can work in tandem to achieve the same result?)
You can disable edge gestures while your app is active and full screen by setting the System.EdgeGesture.DisableTouchWhenFullScreen property on the window.
I don't know if Java provides a direct way to set this (probably not), but you should be able to set this from a JNI.
Here's a C++ snippet from the DisableTouchWhenFullScreen docs:
HRESULT SetTouchDisableProperty(HWND hwnd, BOOL fDisableTouch)
{
IPropertyStore* pPropStore;
HRESULT hrReturnValue = SHGetPropertyStoreForWindow(hwnd, IID_PPV_ARGS(&pPropStore));
if (SUCCEEDED(hrReturnValue))
{
PROPVARIANT var;
var.vt = VT_BOOL;
var.boolVal = fDisableTouch ? VARIANT_TRUE : VARIANT_FALSE;
hrReturnValue = pPropStore->SetValue(PKEY_EdgeGesture_DisableTouchWhenFullscreen, var);
pPropStore->Release();
}
return hrReturnValue;
}
What I ended up doing was to write a batch script that kills explorer.exe and then re-spawns it after the app exits, based on this answer on Super User.

How to simulate a real mouse click using java?

I'm attempting to perform a mouse click in Java, to click something in an external program. To do this, I'm using java.awt.robot, and the following code:
Robot bot = new Robot();
int mask = InputEvent.MOUSE_BUTTON1_DOWN;
bot.mouseMove(x, y);
bot.mousePress(mask);
bot.mouseRelease(mask);
Here's the problem. The external program is able to detect that this click is computer-generated and not human-generated, and hence, its rejecting this click.
I have already tried moving the mouse there naturally and that didn't have any effect. So my guess is, that it must be listening to the keyboard state or such, and telling from that, that the click is computer generated.
What do I have to do to set all keyboard / mouse states to act in the same way as a normal mouse click would?
Well I had the same exact requirement, and Robot class is perfectly fine for me. It works on windows 7 and XP (tried java 6 & 7).
public static void click(int x, int y) throws AWTException{
Robot bot = new Robot();
bot.mouseMove(x, y);
bot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
bot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
}
May be you could share the name of the program that is rejecting your click?
FYI, in newer versions of Windows, there's a new setting where if a program is running in Adminstrator mode, then another program not in administrator mode, cannot send any clicks or other input events to it. Check your source program to which you are trying to send the click (right click -> properties), and see if the 'run as administrator' checkbox is selected.
it works in Linux. perhaps there are system settings which can be changed in Windows to allow it.
jcomeau#aspire:/tmp$ cat test.java; javac test.java; java test
import java.awt.event.*;
import java.awt.Robot;
public class test {
public static void main(String args[]) {
Robot bot = null;
try {
bot = new Robot();
} catch (Exception failed) {
System.err.println("Failed instantiating Robot: " + failed);
}
int mask = InputEvent.BUTTON1_DOWN_MASK;
bot.mouseMove(100, 100);
bot.mousePress(mask);
bot.mouseRelease(mask);
}
}
I'm assuming InputEvent.MOUSE_BUTTON1_DOWN in your version of Java is the same thing as InputEvent.BUTTON1_DOWN_MASK in mine; I'm using 1.6.
otherwise, that could be your problem.
I can tell it worked because my Chrome browser was open to http://docs.oracle.com/javase/7/docs/api/java/awt/Robot.html when I ran the program, and it changed to Debian.org because that was the link in the bookmarks bar at (100, 100).
[added later after cogitating on it today]
it might be necessary to trick the listening program by simulating a smoother mouse movement. see the answer here: How to move a mouse smoothly throughout the screen by using java?
With all respect the most likely thing is that you are mistaken about why the click is being 'rejected'. Why do you think some program is trying to determine if it's human or not? The Robot class (have used it a lot) should send messages that the operating system has no way to distinguish from a user doing the click.
Some applications may detect click source at low OS level. If you really need that kind of hack, you may just run target app in virtual machine's window, and run cliker in host OS, it can help.
You could create a simple AutoIt Script that does the job for you, compile it as an executable and perform a system call there.
in au3 Script:
; how to use: MouseClick ( "button" [, x, y [, clicks = 1 [, speed = 10]]] )
MouseClick ( "left" , $CmdLine[1], $CmdLine[1] )
Now find aut2exe in your au3 Folder or find 'Compile Script to .exe' in your Start Menu and create an executable.
in your Java class call:
Runtime.getRuntime().exec(
new String[]{
"yourscript.exe",
String.valueOf(mypoint.x),
String.valueOf(mypoint.y)}
);
AutoIt will behave as if it was a human and won't be detected as a machine.
Find AutoIt here: https://www.autoitscript.com/

Categories

Resources