在X中获取活动的窗口标题 [英] Get active window title in X

查看:235
本文介绍了在X中获取活动的窗口标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取活动窗口的标题.该应用程序是一个后台任务,因此如果用户打开了Eclipse,该函数将返回"Eclipse-blabla",因此它不会获得我自己窗口的窗口标题.我正在使用PyQt4在Python 2.6中进行开发.

I'm trying to get the title of the active window. The application is a background task so if the user has Eclipse open the function returns "Eclipse - blabla", so it's not getting the window title of my own window. I'm developing this in Python 2.6 using PyQt4.

我目前的解决方案是从SO的一个旧答案中借来的,并稍作修改,看起来像这样:

My current solution, borrowed and slightly modified from an old answer here at SO, looks like this:

def get_active_window_title():
    title = ''
    root_check = ''

    root = Popen(['xprop', '-root'],  stdout=PIPE)

    if root.stdout != root_check:
        root_check = root.stdout

        for i in root.stdout:
            if '_NET_ACTIVE_WINDOW(WINDOW):' in i:
                id_ = i.split()[4]
                id_w = Popen(['xprop', '-id', id_], stdout=PIPE)

        for j in id_w.stdout:
            if 'WM_ICON_NAME(STRING)' in j:
                if title != j.split()[2]:
                    return j.split("= ")[1].strip(' \n\"')

它适用于大多数窗口,但不是全部.例如,它找不到我的kopete聊天窗口或我当前正在开发的应用程序的名称.

It works for most windows, but not all. For example it can't find my kopete chat windows, or the name of the application i'm currently developing.

我的下一次尝试如下:

def get_active_window_title(self):
    screen = wnck.screen_get_default()
    if screen == None:
        return "Could not get screen"
    window = screen.get_active_window()
    if window == None:
        return "Could not get window"
    title = window.get_name()
    return title;

但是出于某些原因,窗口始终为无.

But for some reason window is always None.

有人有更好的方法来获取当前的窗口标题,或者如何修改我的方法之一,以适用于所有窗口?

Does somebody have a better way of getting the current window title, or how to modify one of my ways, that works for all windows?

如果有人想知道这是我发现对所有窗口都适用的方式.

In case anybody is wondering this is the way I found that seems to work for all windows.

def get_active_window_title(self):
    root_check = ''
    root = Popen(['xprop', '-root'],  stdout=PIPE)

    if root.stdout != root_check:
        root_check = root.stdout

        for i in root.stdout:
            if '_NET_ACTIVE_WINDOW(WINDOW):' in i:
                id_ = i.split()[4]
                id_w = Popen(['xprop', '-id', id_], stdout=PIPE)
        id_w.wait()
        buff = []
        for j in id_w.stdout:
            buff.append(j)

        for line in buff:
            match = re.match("WM_NAME\((?P<type>.+)\) = (?P<name>.+)", line)
            if match != None:
                type = match.group("type")
                if type == "STRING" or type == "COMPOUND_TEXT":
                    return match.group("name")
        return "Active window not found"

推荐答案

xdotool 可以做到.

xdotool can do that.

xdotool getactivewindow

这篇关于在X中获取活动的窗口标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆