question

ntnvsl avatar image
0 Votes"
ntnvsl asked Viorel-1 answered

(seems to be) Function pointer loss [Marshal.GetFunctionPointerForDelegate]

My app crashes after several keypresses I make. It's not what I need, of course. Has it something to do with Garbage Collector? I searched online, but I still don't understand exactly how to manage this. How to fix this?

 using System;
 using System.Linq;
 using System.Windows;
 using System.Diagnostics;
 using System.Runtime.InteropServices;
 using FlaUI.UIA3;
 using Application = FlaUI.Core.Application;
 using AutoHotkey.Interop;
    
 namespace random
 {
     public partial class MainWindow : Window
     {
         delegate void Test();
    
         public MainWindow()
         {
             var program = Process.GetProcessesByName("notepad").First();
             var app = Application.Attach(program.Id);
             var mainWindow = app.GetMainWindow(new UIA3Automation());
    
             var ahk = AutoHotkeyEngine.Instance;
    
             Test rand = () => ahk.ExecRaw($"send {(new Random()).Next(100, 200)}");
    
             ahk.ExecRaw("#IfWinActive ahk_exe notepad.exe");
             ahk.ExecRaw($"RCtrl::DllCall({Marshal.GetFunctionPointerForDelegate(rand)})");
    
             InitializeComponent();
         }
     }
 }
dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Viorel-1 avatar image
0 Votes"
Viorel-1 answered

Try moving the variable:

 Test rand;
    
 public MainWindow()
 {
   . . .
   rand = () => ahk.ExecRaw($"send {(new Random()).Next(100, 200)}");
   . . .  
 }



5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.