java 默认焦点,如何把焦点从默认的程序打开文件,从Java?

From within Java, I am opening an Excel file with the default file handler (MS Excel, in this case :-) ) using the method described in this stackoverflow question:

Desktop dt = Desktop.getDesktop();

dt.open(new File(filename));

However, the Excel program doesn't get the focus. Is there any easy way to do so?

Edit: There is a related stackoverflow question for C#, but I didn't find any similar Java method.

Edit 2: I've did some simple tests, and discovered that Excel starts and gets the focus whenever no instance of Excel is running. When Excel is already open en NOT minimized, the application doesn't get the focus. If instead the Excel Windows was minimized, the above code will trigger a maximization of the window and Excel getting the focus (or vice versa :-) ).

解决方案

If you only care about Windows (implied in the question), you can change the way you invoke Excel: use "cmd start...".

I have been using this piece of code to launch Windows applications for some time now. Works every time. It relies on the file association in Windows to find the application. The launched application becomes the focused window on the desktop.

In your case, Excel should be associated with .xls, .csv and other typical extensions. If it is, Windows will launch Excel, passing your file to it.

Usage:

MyUtilClass.startApplication( "c:\\mydir\\myfile.csv", "my window title" );

file is the full path to the input file for Excel and title is the window title (the application may or may not take it - Excel changes the window title).

public static void startApplication( String file, String title )

{

try

{

Runtime.getRuntime().exec( new String[] { "cmd", "/c", "start", title, file } );

}

catch( Exception e )

{

System.out.println( e.getMessage() );

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值