Skip to content

Instantly share code, notes, and snippets.

@freakboy3742
Created September 29, 2019 17:02
Show Gist options
  • Save freakboy3742/552fa5dec922b7150de91a4321689791 to your computer and use it in GitHub Desktop.
Save freakboy3742/552fa5dec922b7150de91a4321689791 to your computer and use it in GitHub Desktop.
IMessageFilter on Python.net
import clr
clr.AddReference("System.Windows.Forms")
import System.Windows.Forms as WinForms
class MessageFilter(WinForms.IMessageFilter):
__namespace__ = 'System.Windows.Forms'
def PreFilterMessage(self, message):
print('filter', message)
return False
class HelloApp(WinForms.Form):
def __init__(self):
self.textbox = WinForms.TextBox()
self.textbox.Text = "Hello World"
self.Controls.Add(self.textbox)
def main():
form = HelloApp()
app = WinForms.Application
f = MessageFilter()
app.AddMessageFilter(f)
app.Run(form)
if __name__ == '__main__':
main()
@freakboy3742
Copy link
Author

freakboy3742 commented Sep 29, 2019

Here's a minimal demo app for installing a custom IMessageFilter in a Winforms app. If you run this code as presented, the application window displays, but you get a segfault immediately (I presume this is when the first message is passed to the filter).

If you comment out line 25 (installing the actual filter), the code works fine.

If you modify MessageFilter so that it doesn't subclass Winforms.IMessageFilter, you get an error at line 25 saying there's no AddMessageFilter method matching the given arguments.

If you rename or remove the PreFilterMessage() method, you get an error that the Python object doesn't have a PreFilterMessage method.

Any suggestions on what I'm doing wrong, and/or how to fix it?

@freakboy3742
Copy link
Author

For those that find this GIST - the problem was identified as pythonnet/pythonnet#965

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment