Search Results

Search found 26 results on 2 pages for 'win32com'.

Page 1/2 | 1 2  | Next Page >

  • Why is win32com so much slower than xlrd?

    - by Josh
    I have the same code, written using win32com and xlrd. xlrd preforms the algorithm in less than a second, while win32com takes minutes. Here is the win32com: def makeDict(ws): """makes dict with key as header name, value as tuple of column begin and column end (inclusive)""" wsHeaders = {} # key is header name, value is column begin and end inclusive for cnum in xrange(9, find_last_col(ws)): if ws.Cells(7, cnum).Value: wsHeaders[str(ws.Cells(7, cnum).Value)] = (cnum, find_last_col(ws)) for cend in xrange(cnum + 1, find_last_col(ws)): #finds end column if ws.Cells(7, cend).Value: wsHeaders[str(ws.Cells(7, cnum).Value)] = (cnum, cend - 1) break return wsHeaders And the xlrd def makeDict(ws): """makes dict with key as header name, value as tuple of column begin and column end (inclusive)""" wsHeaders = {} # key is header name, value is column begin and end inclusive for cnum in xrange(8, ws.ncols): if ws.cell_value(6, cnum): wsHeaders[str(ws.cell_value(6, cnum))] = (cnum, ws.ncols) for cend in xrange(cnum + 1, ws.ncols):#finds end column if ws.cell_value(6, cend): wsHeaders[str(ws.cell_value(6, cnum))] = (cnum, cend - 1) break return wsHeaders

    Read the article

  • python win32com EXCEL data input error

    - by Rafal
    Welcome, I'm exporting results of my script into Excel spreadsheet. Everything works fine, I put big sets of data into SpreadSheet, but sometimes an error occurs: File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 550, in __setattr__ self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value) pywintypes.com_error: (-2147352567, 'Exception.', (0, None, None, None, 0, -2146777998), None)*** I suppose It's not a problem of input data format. I put several different types of data strings, ints, floats, lists and it works fine. When I run the sript for the second time it works fine - no error. What's going on? PS. This is code that generates error, what's strange is that the error doesn't occur always. Say 30% of runs results in an error. : import win32com.client def Generate_Excel_Report(): Excel=win32com.client.Dispatch("Excel.Application") Excel.Workbooks.Add(1) Cells=Excel.ActiveWorkBook.ActiveSheet.Cells for i in range(100): Row=int(35+i) for j in range(10): Cells(int(Row),int(5+j)).Value="string" for i in range(100): Row=int(135+i) for j in range(10): Cells(int(Row),int(5+j)).Value=32.32 #float Generate_Excel_Report() The strangest for me is that when I run the script with the same code, the same input many times, then sometimes an error occurs, sometimes not. Thanks in advance for any help

    Read the article

  • How to open write reserved excel file in python with win32com?

    - by user261935
    Hello, I'm trying to open a write-protected ms excel 2007 file using win32com in python -- I know the password. I can open it with user input of the password into the excel dialog box. I want to be able to open the file without any user interaction. I've tried the following, but it still pops up the dialog box. app.Workbooks.Open("filename.xls", WriteResPassword="secret") Any ideas what I'm doing wrong please? Thanks, Dave.

    Read the article

  • How to convert Word to images with win32com in python?

    - by SpawnCxy
    Hi all, I have googled an example for converting Word to Html. import win32com from win32com.client import Dispatch, constants w = win32com.client.Dispatch('Word.Application') w = win32com.client.DispatchEx('Word.Application') '''skip some code here''' wc = win32com.client.constants w.ActiveDocument.SaveAs( FileName = filenameout, FileFormat = wc.wdFormatHTML ) I tried looking for something like wc.wdFormatPNG as wc.wdFormatHTML in the example but failed.And I wonder does the attribute exist?Or any other better solutions?Suggestions would be appreciated.

    Read the article

  • Python win32com - Automating Word - How to replace text in a text box?

    - by Greg
    I'm trying to automate word to replace text in a word document using Python. (I'm on word 2003 if that matters and Python 2.4) The first part of my replace method below works on everything except text in text boxes. The text just doesn't get selected. I notice when I go into Word manually and hit ctrl-A all of the text gets selected except for the text box. Here's my code so far: class Word: def __init__(self,visible=0,screenupdating=0): pythoncom.CoInitialize() self.app=gencache.EnsureDispatch(WORD) self.app.Visible = visible self.app.DisplayAlerts = 0 self.app.ScreenUpdating = screenupdating print 'Starting word' def open(self,doc): self.opendoc=os.path.basename(doc) self.app.Documents.Open(FileName=doc) def replace(self,source,target): if target=='':target=' ' alltext=self.app.Documents(self.opendoc).Range(Start=0,End=self.app.Documents(self.opendoc).Characters.Count) #select all alltext.Find.Text = source alltext.Find.Replacement.Text = target alltext.Find.Execute(Replace=1,Forward=True) #Special handling to do replace in text boxes #http://word.tips.net/Pages/T003879_Updating_a_Field_in_a_Text_Box.html for shp in self.app.Documents(self.opendoc).Shapes: if shp.TextFrame.HasText: shp.TextFrame.TextRange.Find.Text = source shp.TextFrame.TextRange.Find.Replacement.Text = target shp.TextFrame.TextRange.Find.Execute(Replace=1,Forward=True) #My Usage word=Word(visible=1,screenupdating=1) word.open(r'C:\Invoice Automation\testTB.doc') word.replace('[PGN]','1') The for shp in self.app .. section is my attempt to hit the text boxes. It seems to find the text box, but it doesn't replace anything.

    Read the article

  • Introspection of win32com module / pythoncom module

    - by crystal
    Hi, what is the best way to see what all functions that can be performed using pythoncom module? Specifically, i was working with the win32com module to operate upon excel files. I was not able to find introspection for it as we do for the rest of the modules. Can anyone please suggest how can i retrieve this information?

    Read the article

  • Creating a new workbook in Excel from Python breaks

    - by Marcelo Cantos
    I am trying to use the stock standard win32com approach to drive Excel 2007 from Python. However, when I try to create a new workbook, things go pear-shaped: Python 2.6.4 (r264:75706, Nov 3 2009, 13:23:17) [MSC v.1500 32 bit (Intel)] on win32 ... >>> import win32com.client >>> excel = win32com.client.Dispatch("Excel.Application") >>> wb = excel.Workbooks.Add() Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> wb = excel.Workbooks.Add() File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 467, in __getattr__ if self._olerepr_.mapFuncs.has_key(attr): return self._make_method_(attr) File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 295, in _make_method_ methodCodeList = self._olerepr_.MakeFuncMethod(self._olerepr_.mapFuncs[name], methodName,0) File "C:\Python26\lib\site-packages\win32com\client\build.py", line 297, in MakeFuncMethod return self.MakeDispatchFuncMethod(entry, name, bMakeClass) File "C:\Python26\lib\site-packages\win32com\client\build.py", line 318, in MakeDispatchFuncMethod s = linePrefix + 'def ' + name + '(self' + BuildCallList(fdesc, names, defNamedOptArg, defNamedNotOptArg, defUnnamedArg, defOutArg) + '):' File "C:\Python26\lib\site-packages\win32com\client\build.py", line 604, in BuildCallList argName = MakePublicAttributeName(argName) File "C:\Python26\lib\site-packages\win32com\client\build.py", line 542, in MakePublicAttributeName return filter( lambda char: char in valid_identifier_chars, className) File "C:\Python26\lib\site-packages\win32com\client\build.py", line 542, in <lambda> return filter( lambda char: char in valid_identifier_chars, className) UnicodeDecodeError: 'ascii' codec can't decode byte 0x83 in position 52: ordinal not in range(128) >>> What is going wrong here? Have I done something silly, or is Python/win32com/Excel somehow broken?

    Read the article

  • Paste Excel clip to body of an email through Python

    - by Twinkle
    I am using win32com.client in Python to send an email. However I want the body of the email to be a table (HTML- formatted table), I can do it in an Excel first and then copy and paste (but how?), or directly edit the corresponding Pandas data frame. newMail.body = my_table which is a Pandas data frame didn't work. So I'm wondering if there is smarter ways for example, to combine Excel with Outlook apps within Python? Cheers,

    Read the article

  • How to use Mozilla ActiveX Control without registry

    - by Andrew McKinlay
    I've been using the IE Browser component that is part of Windows. But I'm running into problems with security settings. For example, users get security warnings on pages with Javascript. So I'm looking at using the Mozilla ActiveX control instead. It's especially nice because it has a compatible interface. It works well if I let it install the control in the registry. But my users don't always have administrator rights to install things in the registry. So I'm trying to figure out how to use the control without registry changes. I'm using DllGetClassObject to get the class factory (IID_ICLASSFACTORY) and then CoRegisterClassObject to register it. All the API calls appear to succeed. And when I create an AtlAxWin window with the CLSID, it also appears to work. But when I try to call Navigate on the AtlAxGetControl it doesn't work - the interface doesn't have Navigate. I would show the code but it's in an obscure language (Suneido) so it wouldn't mean much. An example in C or C++ would be easy for me to translate. Or an example in another dynamic language like Python or Ruby might be helpful. Obviously I'm doing something wrong. Maybe I'm passing the wrong thing to CoRegisterClassObject? The MSDN documentation isn't very clear on what to pass and I haven't found any good examples. Or if there is another approach, I'm ok with that too. Note: I'm using the AtlAxWin window class so I'm not directly creating the control and can't use this approach. Another option is registry free com with a manifest. But again, I couldn't find a good example, especially since I'm not using Visual Studio. I tried to use the MT manifest tool, but couldn't figure it out. I don't think I can use DLL redirection since that doesn't get around the registry issue AFAIK. Another possibility is using WebKit but it seems even harder to use.

    Read the article

  • How do I search & replace all occurrences of a string in a ms word doc with python?

    - by Mark
    Hello there, I am pretty stumped at the moment. Based on http://stackoverflow.com/questions/1045628/can-i-use-win32-com-to-replace-text-inside-a-word-document I was able to code a simple template system that generates word docs out of a template word doc (in Python). My problem is that text in "Text Fields" is not find that way. Even in Word itself there is no option to search everything - you actually have to choose between "Main Document" and "Text Fields". Being new to the Windows world I tried to browse the VBA docs for it but found no help (probably due to "text field" being a very common term). word.Documents.Open(f) wdFindContinue = 1 wdReplaceAll = 2 find_str = '\{\{(*)\}\}' find = word.Selection.Find find.Execute(find_str, False, False, True, False, False, \ True, wdFindContinue, False, False, False) while find.Found: t = word.Selection.Text.__str__() r = process_placeholder(t, answer_data, question_data) if type(r) == dict: errors.append(r) else: find.Execute(t, False, True, False, False, False, \ True, False, False, r, wdReplaceAll) This is the relevant portion of my code. I was able to get around all problems by myself by now (hint: if you want to replace strings with more than 256 chars, you have to do it via clipboard, etc ...) Hope, someone can help me.

    Read the article

  • Media Kind in iTunes COM for Windows SDK

    - by Joel Verhagen
    I recently found out about the awesomeness of the iTunes COM for Windows SDK. I am using Python with win32com to talk to my iTunes library. Needless to say, my head is in the process of exploding. This API rocks. I have one issue though, how do I access the Media Kind attribute of the track? I looked through the help file provided in the SDK and saw no sign of it. If you go into iTunes, you can modify the track's media kind. This way if you have an audiobook that is showing up in your music library, you can set the Media Kind to Audiobook and it will appear in the Books section in iTunes. Pretty nifty. The reason I ask is because I have a whole crap load of audiobooks that are showing up in my LibraryPlaylist. Here is my code thus far. import win32com.client iTunes = win32com.client.gencache.EnsureDispatch('iTunes.Application') track = win32com.client.CastTo(iTunes.LibraryPlaylist.Tracks.Item(1), 'IITFileOrCDTrack') print track.Artist, '-', track.Name print print 'Is this track an audiobook?' print 'How the hell should I know?' Thanks in advance.

    Read the article

  • wmi not available for some time after reboot

    - by Alex Okrushko
    I'm having the problem with the WMI availability on logon. Right after reboot I open cmd and with python interpreter: >>> import wmi >>> c = wmi.WMI() >>> c.Win32_OperatingSystem() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python27\lib\site-packages\wmi.py", line 1147, in __getattr__ return getattr (self._namespace, attribute) File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 516, in __getattr__ raise AttributeError("%s.%s" % (self._username_, attr)) AttributeError: winmgmts:.Win32_OperatingSystem >>> 5 minutes later I open another cmd and python interpreter: Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> import wmi >>> c = wmi.WMI() >>> c.Win32_OperatingSystem() [<_wmi_object: \\W520-ALEX-WIN7\root\cimv2:Win32_OperatingSystem=@>] >>> NOTE: the first cmd still keeps saying AttributeError even 5 minutes later. NOTE 2: if I logout and login wmi is available, so it is somehow effected by reboot with process explorer I check the environmental variables and they are the same for both cmds What could that be? Please help. UPDATE: Apparently the problem is connecting to the wbem services: >>> import win32com.client >>> win32com.client.Dispatch('WbemScripting.SWbemLocator') <COMObject WbemScripting.SWbemLocator> >>> wmi_service= win32com.client.Dispatch('WbemScripting.SWbemLocator') >>> wbem_service = wmi_service.ConnectServer('.','root/cimv2') >>> wbem_service <COMObject <unknown>> >>> items = wbem_service.ExecQuery('Select * from Win32_OperatingSystem') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<COMObject <unknown>>", line 3, in ExecQuery File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 282, in _ApplyTypes_ result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes ) + args) pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'SWbemServicesEx ', u'Generic failure ', None, 0, -2147217407), None) >>> NOTE 3: wmic os always worked. NOTE 4: re-installing pywin32 package didn't help. Neither did Re-registering/re-compiling the WMI components and resetting of the WMI database (as recommended here) NOTE 5: my 4 Other laptops don't have this problem. Also wmiprov.log has: (Mon Oct 29 11:40:07 2012.248587) : *************************************** (Mon Oct 29 11:40:07 2012.248587) : Could not get pointer to binary resource for file: (Mon Oct 29 11:40:07 2012.248587) : C:\Windows\system32\drivers\ndis.sys[MofResourceName](Mon Oct 29 11:40:07 2012.248587) : (Mon Oct 29 11:40:07 2012.248587) : *************************************** (Mon Oct 29 11:40:07 2012.248587) : *************************************** (Mon Oct 29 11:40:07 2012.248587) : Could not get pointer to binary resource for file: (Mon Oct 29 11:40:07 2012.248587) : C:\Windows\system32\drivers\en-US\ndis.sys.mui[MofResourceName](Mon Oct 29 11:40:07 2012.248587) : (Mon Oct 29 11:40:07 2012.248587) : *************************************** (Mon Oct 29 11:40:07 2012.248603) : *************************************** (Mon Oct 29 11:40:07 2012.248603) : Could not get pointer to binary resource for file: (Mon Oct 29 11:40:07 2012.248603) : C:\Windows\system32\DRIVERS\wmiacpi.sys[MofResource](Mon Oct 29 11:40:07 2012.248603) : (Mon Oct 29 11:40:07 2012.248603) : *************************************** (Mon Oct 29 11:40:07 2012.248603) : *************************************** (Mon Oct 29 11:40:07 2012.248603) : Could not get pointer to binary resource for file: (Mon Oct 29 11:40:07 2012.248603) : C:\Windows\system32\DRIVERS\monitor.sys[MonitorWMI](Mon Oct 29 11:40:07 2012.248603) : (Mon Oct 29 11:40:07 2012.248603) : *************************************** NOTE 6: the WMIDiag tool report is at my dropbox

    Read the article

  • How to properly close a process with NppExec?

    - by Sam the Great
    I'm not sure what's going on here, but the following code continues running even after I end the process in the NppExec console with Ctrl-C (during the execution of the while loop). I restarted my computer to stop the Ctrl key sends. However, if I run the script in Window's cmd prompt, Ctrl-C ends the script just fine. import time import win32com.client shell = win32com.client.Dispatch("WScript.Shell") time.sleep(2) while True: shell.SendKeys('^') # Ctrl key time.sleep(0.5) The NppExec run command I used was: cmd /C python -u "$(FULL_CURRENT_PATH)" Let me know if there is any more information I can provide. Thanks.

    Read the article

  • Generating Mouse-Keyboard combination events in python

    - by freakazo
    I want to be able to do a combination of keypresses and mouseclicks simultaneously, as in for example Control+LeftClick At the moment I am able to do Control and then a left click with the following code: import win32com, win32api, win32con def CopyBox( x, y): time.sleep(.2) wsh = win32com.client.Dispatch("WScript.Shell") wsh.SendKeys("^") win32api.SetCursorPos((x,y)) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0) What this does is press control on the keyboard, then it clicks. I need it to keep the controll pressed longer and return while it's still pressed to continue running the code. Is there a maybe lower level way of saying press the key and then later in the code tell it to lift up the key such as like what the mouse is doing?

    Read the article

  • Setting System.Drawing.Color through .NET COM Interop

    - by Maxim
    I am trying to use Aspose.Words library through COM Interop. There is one critical problem: I cannot set color. It is supposed to work by assigning to DocumentBuilder.Font.Color, but when I try to do it I get OLE error 0x80131509. My problem is pretty much like this one: http://bit.ly/cuvWfc update: Code Sample: from win32com.client import Dispatch Doc = Dispatch("Aspose.Words.Document") Builder = Dispatch("Aspose.Words.DocumentBuilder") Builder.Document = Doc print Builder.Font.Size print Builder.Font.Color Result: 12.0 Traceback (most recent call last): File "aaa.py", line 6, in <module> print Builder.Font.Color File "D:\Python26\lib\site-packages\win32com\client\dynamic.py", line 501, in __getattr__ ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1) pywintypes.com_error: (-2146233079, 'OLE error 0x80131509', None, None) Using something like Font.Color = 0xff0000 fails with same error message While this code works ok: using Aspose.Words; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Font.Color = System.Drawing.Color.Blue; builder.Write("aaa"); doc.Save("c:\\1.doc"); } } } So it looks like COM Interop problem.

    Read the article

  • Error while opening port in Java

    - by Deepak
    I am getting the following error while trying to open the cash drawer. Error loading win32com: java.lang.UnsatisfiedLinkError: C:\Program Files\Java\jdk1.6.0_15\jre\bin\win32com.dll: Can't load IA 32-bit .dll on a AMD 64-bit platform The code i am using is as follows `import javax.comm.; import java.util.; /** Check each port to see if it is open. **/ public class openPort { public static void main (String [] args) { Enumeration port_list = CommPortIdentifier.getPortIdentifiers (); while (port_list.hasMoreElements ()) { // Get the list of ports CommPortIdentifier port_id = (CommPortIdentifier) port_list.nextElement (); // Find each ports type and name if (port_id.getPortType () == CommPortIdentifier.PORT_SERIAL) { System.out.println ("Serial port: " + port_id.getName ()); } else if (port_id.getPortType () == CommPortIdentifier.PORT_PARALLEL) { System.out.println ("Parallel port: " + port_id.getName ()); } else System.out.println ("Other port: " + port_id.getName ()); // Attempt to open it try { CommPort port = port_id.open ("PortListOpen",20); System.out.println (" Opened successfully"); port.close (); } catch (PortInUseException pe) { System.out.println (" Open failed"); String owner_name = port_id.getCurrentOwner (); if (owner_name == null) System.out.println (" Port Owned by unidentified app"); else // The owner name not returned correctly unless it is // a Java program. System.out.println (" " + owner_name); } } } //main } // PortListOpen`

    Read the article

  • R/XLL: Interface to call XLL method in R

    - by Neerav
    I am trying to call the methods defined in the XLL addin(for Excel) from R. Something similar to this Python code: import os from win32com.client import Dispatch Path = 'myxll.xll' xlApp = Dispatch("Excel.Application") xlApp.RegisterXLL(Path) # function call from excel # =xllfunction("param1","param2",...) result = xlApp.run('xllfunction', "param1","param2",...) Is there any library in R that does the XLL interface? Thanks for your help.

    Read the article

  • How can I dispatch Firefox or Google Chrome with Python?

    - by Shady
    How can I do this with Firefox or Google Chrome? ie = win32com.client.Dispatch('InternetExplorer.Application') ie.visible = 1 ie.navigate('http://google.com') Is there a way to do it? ps: I need to use the ReadyState with it... for example while (ie.ReadyState != 4):, or in other words, I need some command that wait until the page loads completely until do the next command, that's why I need the dispatch, that currently work very good with IE

    Read the article

  • Java RS232 Comm on Vista-64 bit

    - by DD
    We have a Java application which needs to communicate with a peripheral device over Virtual Serial COM port. We use the RS232 Java COMM API (javax.comm.properties, comm.jar, win32com.dll) to achieve the same. Currently the code works fine on Windows XP 32-bit, Vista 32-bit and Windows 7. However we are having a problem trying to communicate on Vista 64-bit. I read from the Java forums that there is no 64-bit support for the Java COMM API I was wondering if anyone was facing a similar situation and were able to resolve the same in some way?

    Read the article

  • Is there a way to watch all COM activity on a computer?

    - by Fake Name
    I'm trying to deal with a piece of specialized hardware, that presents it's interface as a COM object, using win32com in Python. However, the documentation for how to actually set up the hardware through the COM object is sparse (it requires a significant amount of initialization), and entirely oriented at using a bunch of pre-built libraries for Visual Studio, which are not accessible through python. That said, is there any way to watch all local COM activity, so I can sort through the activity logs to try and figure out how the existing demo programs properly initialize the hardware, and replicate the behavior in my python script? Ideally, there would be something in the vein of wireshark for doing this. Note: I have very little (read: basically no) experience using COM, as my focus is mostly embedded hardware (and a little python dev on the side). However, I'm stuck with this particular device.

    Read the article

  • Call functions in AutoIt DLL using Python ctypes

    - by Josh
    I want to call functions from an AutoIt dll, that I found at C:\Program Files (x86)\AutoIt3\AutoItX\AutoItX3.dll using Python. I know I could use win32com.client.Dispatch("AutoItX3.Control") but I can't install the application or register anything in the system. So far, this is where I am: from ctypes import * path = r"C:\Program Files (x86)\AutoIt3\AutoItX\AutoItX3.dll" autoit = windll.LoadLibrary(path) Here are the methods that works: autoit.AU3_WinMinimizeAll() # windows were successfully minimized. autoit.AU3_Sleep(1000) # sleeps 1 sec. Here is my problem, python is crashing when I call other methods like this one. I get python.exe has stopped working from windows... autoit.AU3_WinGetHandle('Untitled - Notepad', '') And some other methods are not crashing python but are just not working. This one doesn't close the window and return 0: autoit.AU3_WinClose('Untitled - Notepad', '') And this other one return 1 but the window is still minimized: autoit.AU3_WinActivate('Untitled - Notepad', '') I've tested the examples with with Dispatch("AutoItX3.Control") and everything is working like expected. It seems like methods that should return something other than a string are crashing python. But still, others like WinClose are not even working... Thank you in advance for your help! EDIT: These methods are now working when using unicode strings: autoit.AU3_WinClose(u'Untitled - Notepad', u'') autoit.AU3_WinActivate(u'Untitled - Notepad', u'') And I found the prototype for AU3_WinGetHandle: AU3_API void WINAPI AU3_WinGetHandle(const char szTitle, /[in,defaultvalue("")]*/const char *szText, char *szRetText, int nBufSize); Now I see that I should get the handle from szRetText but I am not sure how... I tried the following without success: from ctypes.wintypes import LPCWSTR, INT, POINTER AU3_WinGetHandle.argtypes = (LPCWSTR, LPCWSTR, POINTER(LPCWSTR), INT) s = c_wchar_p() print AU3_WinGetHandle(u'Untitled - Notepad', u'', byref(s), 100) # prints 1 print s # prints c_wchar_p(u'') Any idea how to retrive the handle from szRetText?

    Read the article

  • Using Sendkeys in python to press {F12} results in other keys pressed?

    - by ThantiK
    import time from ctypes import * import win32gui import win32com.client as comclt X = 119 Y = 53 def PILColorToRGB(pil_color): """ convert a PIL-compatible integer into an (r, g, b) tuple """ hexstr = '%06x' % pil_color # reverse byte order r, g, b = hexstr[4:], hexstr[2:4], hexstr[:2] r, g, b = [int(n, 16) for n in (r, g, b)] return (r, g, b) wsh = comclt.Dispatch("WScript.Shell") w = win32gui user = windll.LoadLibrary("c:\\windows\\system32\\user32.dll") h = user.GetDC(0) gdi = windll.LoadLibrary("c:\\windows\\system32\\gdi32.dll") while True: FG = w.GetWindowText(w.GetForegroundWindow()) #FG = Foreground window title. if FG == "World of Warcraft": rgb = (PILColorToRGB(gdi.GetPixel(h,X,Y))) #X, Y time.sleep(0.333) #don't check too often. if (rgb[0] >= 130): #While Pixel (X, Y) is Red... #print "%d %d %d" % (rgb[0], rgb[1], rgb[2]) #Debug wsh.SendKeys("{F12}") #Send a key. time.sleep(0.7) #Add some extra down-time if we send the key. else: time.sleep(5) Basically all this code does is read a pixel on the screen, and send a key (F12) if the pixel is red. But when using this code I regularly get some phantom key-code being pressed. The application I'm using this on is obviously world of warcraft, and I have checked that all keybinds are standard keybinds. However randomly it seems I get either an up arrow, or a w pressed, which moves my character forward whenever this code executes (F12 is bound to a macro, unbound from any movement. If I press f12 with a hardware event, it does not exhibit this behavior. What in the world could be going on here?

    Read the article

  • Monitor web sites visited using Internet Explorer, Opera, Chrome, Firefox and Safari in Python

    - by Zachary Brown
    I am working on a project for work and have seemed to run into a small problem. The project is a similar program to Web Nanny, but branded to my client's company. It will have features such as website blocking by URL, keyword and web activity logs. I would also need it to be able to "pause" downloads until an acceptable username and password is entered. I found a script to monitor the URL visited in Internet Explorer (shown below), but it seems to slow the browser down considerably. I have not found any support or ideas onhow to implement this in other browsers. So, my questions are: 1). How to I monitor other browser activity / visited URLs? 2). How do I prevent downloading unless an acceptable username and password is entered? from win32com.client import Dispatch,WithEvents import time,threading,pythoncom,sys stopEvent=threading.Event() class EventSink(object): def OnNavigateComplete2(self,*args): print "complete",args stopEvent.set() def waitUntilReady(ie): if ie.ReadyState!=4: while 1: print "waiting" pythoncom.PumpWaitingMessages() stopEvent.wait(.2) if stopEvent.isSet() or ie.ReadyState==4: stopEvent.clear() break; time.clock() ie=Dispatch('InternetExplorer.Application',EventSink) ev=WithEvents(ie,EventSink) ie.Visible=1 ie.Navigate("http://www.google.com") waitUntilReady(ie) print "location",ie.LocationName ie.Navigate("http://www.aol.com") waitUntilReady(ie) print "location",ie.LocationName print ie.LocationName,time.clock() print ie.ReadyState

    Read the article

1 2  | Next Page >